/******************************************************/
/************************ Content  ********************/
/*

Additional graphs and tables
1 - Substitution between referal criteria graphs
2 - Additional summary statistics
3 - Additional mental health outcomes table
4 - IV estimates on mental health outcomes table
5 - RD-DiD illustration graphs
6 - RD illustration graphs
7 - Effects on psychiatric hospital contacts by diagnosis
8 - Share of suicide attempts that are successful
9 - Drug results by prescriber
10 - RD-DID (by year) graph for suicide attempts
11 - Long-run effects on mental health outcomes
12 - Labor market graphs
13 - Yearly labor market outcomes table
14 - Yearly labor market graphs
15 - Physical health results within two years

Heterogeneity
16 - By gender: Effects on mental health outcomes 
17 - By income: Effects on mental health outcomes
18 - By fam MH: Effects on mental health outcomes

19 - By gender: Effects on physical health outcomes 
20 - By income: Effects on physical health outcomes
21 - By fam MH: Effects on physical health outcomes

22 - By gender: Effects on labor market outcomes 
23 - By income: Effects on labor market outcomes 
24 - By fam MH: Effects on labor market outcomes 

Robustness
25 - Alternative models: Mental health outcomes - Illustration detrended DID
26 - Alternative models: Mental health outcomes - Table, RD-Time--DID and detrended DID
27 - Alternative models: Physical health outcomes - Table, ES-RD-DID and ES-DID

28 - Choice of bandwidth: Mental health outcomes
29 - Choice of bandwidth: Physical health outcomes

30 - Placebo age cutoffs: Mental health outcomes
31 - Placebo age cutoffs: Physical health outcomes
32 - Placebo pre-post estimates: Physical health outcomes

33 - Sample selection in ES models: Pre-treatment differences
34 - Sample selection in ES models: Controlling for event-time-specific outcome preds
35 - Sample selection in ES models: Alternative definition of mental health shocks

36 - Full-population data and methods: Physical health outcomes
37 - Full-population data and methods: Labor market outcomes

*/
/******************************************************/


/*********************/
/********* 1 *********/
/*********************/

** RD Graphs **
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if (year==2011 & month>=7 & !mi(month)) |  (year==2012 & month<7)
keep if inrange(agec,21,50)
keep pnr year month age agec hen19 hen10 hen11 firstpsyc Dpsyc

foreach var in hen19 hen10 hen11 {

replace `var'=0 if mi(`var')
cap drop D`var'
gen D`var'=(`var'>0)
}

cap drop Dhen1910
gen Dhen1910=(Dhen10==1 | Dhen19==1)

* Convert to yearly estimates *
foreach var in Dhen19 Dhen10 Dhen11 Dhen1910 Dpsyc {

cap drop max sum share
bysort pnr: gegen max=max(`var') 
by pnr: gegen sum=sum(`var') 
gen share=sum/max

qui sum share

replace `var'=`var'*(12/r(mean))
}

pause on
preserve

gcollapse (mean)  Dhen19 Dhen10 Dhen11 Dhen1910 Dpsyc if inrange(age,0,60), by(agec) fast

replace agec=floor(agec*2)/2
collapse (mean)  Dhen19 Dhen10 Dhen11 Dhen1910 Dpsyc if inrange(age,0,60), by(agec) fast

foreach var in Dhen19 Dhen10 Dhen11 Dhen1910 Dpsyc  {
replace `var'=`var'*100
}

/* Depresssion/Anxiety to other at age 38 */
twoway (scatter Dhen19 agec if  inrange(agec,30,46) & agec!=38, mcolor(red)) ///
	  ,xline(38, lcolor(red)) graphregion(color(white)) /*text(0.17 33.5 "Coefficient:${dires2}" " " "T-stat: ${dise2}" , box lcolor(white) fcolor(white))*/ ///
	  legend(off) xtitle("Age") ytitle("Percent in psychological treatment, criteria 1-9") ///
	  xscale(titlegap(*4)) yscale(titlegap(*6)) xsize(5) ysize(5) 

graph export I:\workdata\706727\Figs\Final_Appendix_SubRef_DeptoOther38.png, width(2000) replace
graph export I:\workdata\706727\Figs\Final_Appendix_SubRef_DeptoOther38.eps,  replace

/* Anxiety to Dep at age 29 */
twoway (scatter Dhen11 agec if  inrange(agec,22,36) & agec!=29, mcolor(red) yaxis(1)) ///
		(scatter Dhen10 agec if inrange(agec,22,36) & agec!=29, mcolor(navy) ms(square) yaxis(2)) ///
	  ,xline(29, lcolor(red)) graphregion(color(white)) /*text(0.38 27.35 "Coefficient:${dires3}" " " "T-stat: ${dise3}" , box lcolor(white) fcolor(white))*/ ///
	  xtitle("Age") ytitle("Percent in psychological treatment", axis(1)) ytitle("Percent in psychological treatment", axis(2)) ///
	  xscale(titlegap(*4)) yscale(titlegap(*6) axis(1)) yscale(titlegap(*6) axis(2)) xsize(5) ysize(5) xlabel(22(2)36) ylabel(-0.2(0.2)0.9, axis(1)) ylabel(1.8(0.2)2.9, axis(2)) ///
	  legend(label(2 "Depression (right axis)") label(1 "Anxiety (left axis)         ") rows(1) region(color(white) margin(medlarge)) ring(0) pos(11) size(small))

graph export I:\workdata\706727\Figs\Final_Appendix_SubRef_AnxtoDep29.png, width(2000) replace
graph export I:\workdata\706727\Figs\Final_Appendix_SubRef_AnxtoDep29.eps,  replace

restore

** Introduction of anxiety criterion **
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_YearCollapse

keep if inrange(year,2000,2013)
keep if minagec>18 & maxagec<50 & !mi(minagec) & !mi(maxagec) 
drop if minagec<=38 & maxagec>=38


/* Generate variables */
cap drop treat
gen treat=0 if inrange(maxagec,38,50)
replace treat=1 if inrange(maxagec,18,28)
replace treat=2 if inrange(maxagec,29,37)

replace firstpsyc=firstpsyc*100

cap postclose john

postfile john treat year koef lower upper using "I:\Workdata\706727\Figs\Final_FirstStage\Final_Appendix_AnxietyIntroDID" ,replace

qui reg firstpsyc ibn.year#ibn.treat , noconstant vce(cluster pnr)

foreach t in 0 1 2 {
	forvalues yr=2000/2013 {
	post john (`t') (`yr') (_b[`yr'.year#`t'.treat]) (_b[`yr'.year#`t'.treat]-1.96*_se[`yr'.year#`t'.treat]) (_b[`yr'.year#`t'.treat]+1.96*_se[`yr'.year#`t'.treat])
	}
}
postclose john


/* Create figure */
clear 
use "I:\Workdata\706727\Figs\Final_FirstStage\Final_Appendix_AnxietyIntroDID"


/* Raw */
twoway (line lower upper year if treat==0 , lcolor(black black) lpattern(dash dash)) ///
	   (line lower upper year if treat==1 , lcolor(red*0.9 red*0.9) lpattern(dash dash)) ///
	   (line lower upper year if treat==2 , lcolor(green*0.5 green*0.5) lpattern(dash dash)) ///
	   (connect koef year if treat==0, color(black) lwidth(*2)) (connect koef year if treat==1, color(red*0.9) lwidth(*2)) ///
	   (connect koef year if treat==2, color(green*0.5) lwidth(*2)), ///
graphregion(color(white)) xline(2008 2011 2012, lcolor(black) lp(dash))  xlabel(2000(2)2012) xtitle("") ytitle(Share starting psychological treatment) ///
legend(order(9 "Treatment: age 29-37" 8 "Treatment: age 18-28"  7 "Control:      age 38-50") ring(0) region(color(white)) pos(11) rows(3) symxsize(huge) symysize(thick)) ///
xscale(titlegap(*4)) yscale(titlegap(*6)) xsize(8) ysize(5)

graph export "I:\Workdata\706727\Figs\Final_Appendix_AnxietyIntroDID.png",replace width(2000)
graph export "I:\Workdata\706727\Figs\Final_Appendix_AnxietyIntroDID.eps", replace


/*********************/
/********* 2 *********/
/*********************/

/* Treatment initiations - mental health care services */
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_YearCollapse

keep if inrange(year,2000,2007)
gen age =floor(minagec)
keep if inrange(age,0,58)

gen byte firstbamb=Dbamb*firstpsykhosp
gen byte firsterp=Derp*firstpsykhosp
gen byte firstPHosp=DPHosp*firstpsykhosp

replace firstbamb=0 if firstPHosp==1
replace firsterp=0 if firstPHosp==1 | firstbamb==1 
replace firstpsychiatry=0 if firsterp==1 | firstPHosp==1 | firstbamb==1
replace firstpsyc=0 if firstpsychiatry==1 | firsterp==1 | firstPHosp==1 | firstbamb==1
replace firsttherapy=0 if firstpsyc==1 | firstpsychiatry==1 | firsterp==1 | firstPHosp==1 | firstbamb==1

collapse (mean) firstbamb firstpsyc firsttherapy firstpsychiatry firsterp firstPHosp , by(age) fast

replace firsttherapy=firsttherapy
replace firstpsyc=firstpsyc+firsttherapy
replace firstpsychiatry=firstpsychiatry+firstpsyc
replace firsterp=firsterp+firstpsychiatry
replace firstbamb=firstbamb+firsterp
replace firstPHosp=firstPHosp+firstbamb

foreach var in firstPHosp firstbamb firsterp firstpsychiatry firstpsyc firsttherapy {
replace `var'=`var'*100
}

twoway (area firstPHosp firstbamb firsterp firstpsychiatry firstpsyc firsttherapy age), graphregion(color(white)) ///
legend(label(1 "Inpatient Psyc. Hosp.") label(2 "Outpatient Psyc. Hosp.") label(3 "ER Psyc. Hosp.") ///
 label(4 "Psychiatrist") label(5 "Psychologist") label(6 "PCP MHC") cols(1) region(color(none)) size(small) symxsize(small) ring(0) pos(11) keygap(*0.5)) ///
 xtitle("Age") ytitle("Percent of the population") ylabel(0(1)5) ///
xsize(5) ysize(5) yscale(titlegap(*4))

graph export I:\Workdata\706727\Figs\FirstMentalServicesFigure.eps , replace 
graph export I:\Workdata\706727\Figs\FirstMentalServicesFigure.png , replace width(2000)


/* Treatment initiations - Prescription drugs */
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_YearCollapse

keep if inrange(year,2000,2007)
gen age=floor(minagec)
keep if inrange(age,0,58)

gen firstotherpsykmed=(firstpsykmed==1 & firstanxiety==0 & firstsleep==0 & firstadep==0)
replace firstanxiety=0 if firstsleep==1 | firstadep==1 
replace firstsleep=0 if  firstadep==1 

gcollapse (mean) firstotherpsykmed firstanxiety firstsleep firstadep  , by(age) fast

replace firstanxiety=firstanxiety+firstsleep+firstadep
replace firstotherpsykmed=firstotherpsykmed+firstanxiety

foreach var in  firstotherpsykmed firstanxiety firstadep {
replace `var'=`var'*100
}

twoway (area firstotherpsykmed firstanxiety firstadep  age), graphregion(color(white)) ///
 xtitle("Age") ytitle("Percent of the population") ///
 legend(label(3 "Antidepressants")  ///
		label(2 "Anxiety and tranquilizers") label(1 "Other psychiatric meds") ///
		cols(1) region(color(white)) size(small) ring(0) pos(11) symxsize(small) keygap(*0.5)) ///
		xsize(5) ysize(5) yscale(titlegap(*4))

graph export I:\Workdata\706727\Figs\FirstMentalServicesFigure_Drugs.eps , replace 
graph export I:\Workdata\706727\Figs\FirstMentalServicesFigure_Drugs.png , replace width(2000)

/* Psykhosp Diags selected */
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_YearCollapse

keep if inrange(year,2000,2007)
gen age=floor(minagec)
keep if inrange(age,0,58)

gen Dother=Dpsykhosp_0==1 | Dpsykhosp_5==1 | Dpsykhosp_6==1 | Dpsykhosp_7==1 | Dpsykhosp_8==1 | Dpsykhosp_9==1 

replace  Dpsykhosp_4=0 if Dpsykhosp_1==1 | Dpsykhosp_2==1 | Dpsykhosp_3==1 | Dother==1
replace  Dpsykhosp_3=0 if Dpsykhosp_1==1 | Dpsykhosp_2==1 | Dother==1
replace  Dpsykhosp_1=0 if Dpsykhosp_2==1 | Dother==1
replace  Dpsykhosp_2=0 if Dother==1

collapse (mean) Dpsykhosp_1 Dpsykhosp_2 Dpsykhosp_3 Dpsykhosp_4 Dother (sum) sumDpsykhosp_1=Dpsykhosp_1 sumDpsykhosp_2=Dpsykhosp_2 sumDpsykhosp_3=Dpsykhosp_3 sumDpsykhosp_4=Dpsykhosp_4 sumDother=Dother, by(age) fast

replace Dpsykhosp_3=Dpsykhosp_3+Dpsykhosp_4
replace Dpsykhosp_2=Dpsykhosp_2+Dpsykhosp_3
replace Dpsykhosp_1=Dpsykhosp_1+Dpsykhosp_2
replace Dother=Dother+Dpsykhosp_1

foreach var in Dpsykhosp_1 Dpsykhosp_2 Dpsykhosp_3 Dpsykhosp_4 Dother {
replace `var'=`var'*100
}
foreach var in Dpsykhosp_1 Dpsykhosp_2 Dpsykhosp_3 Dpsykhosp_4 Dother {
replace `var'=. if sum`var'<=5
}

twoway (area Dother Dpsykhosp_1 Dpsykhosp_2 Dpsykhosp_3 Dpsykhosp_4 age), graphregion(color(white)) ///
 xtitle("Age") ytitle("Percent") ///
 legend(label(2 "Substance use") label(3 "Schizophrenia") label(4 "Depression") ///
		label(5 "Anxiety")  label(1 "Other")  ///
		cols(1) region(color(none)) size(small) ring(0) pos(11) symxsize(small) keygap(*0.5)) ylabel(0(0.5)2.25) ///
		xsize(5) ysize(5) yscale(titlegap(*4))

graph export I:\Workdata\706727\Figs\MentalServicesFigure_PsykhospDiag.eps , replace 
graph export I:\Workdata\706727\Figs\MentalServicesFigure_PsykhospDiag.png , replace width(2000)

/* Severity of depression */
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_YearCollapse

keep if inrange(year,2000,2007)
gen age=floor(minagec)
keep if inrange(age,0,58)

tab DepSev, gen(DepD)

gcollapse (mean) DepD* (sum) sumDepD1=DepD1 sumDepD2=DepD2 sumDepD3=DepD3 sumDepD4=DepD4, by(age) fast

replace DepD3=DepD2+DepD3
replace DepD4=DepD3+DepD4
replace DepD1=DepD4+DepD1

foreach var in 1 2 3 4 {
replace DepD`var'=DepD`var'*100
}
foreach var in 1 2 3 4 {
replace DepD`var'=. if sumDepD`var'<=5
}

twoway (area DepD1 DepD4 DepD3 DepD2 age), graphregion(color(white)) ///
 xtitle("Age") ytitle("Percent of depression patients") ///
 legend(label(4 "Mild") label(3 "Moderate") label(2 "Severe") ///
		label(1 "Unknown") ///
		cols(1) region(color(white)) size(small) ring(0) pos(11) symxsize(small) keygap(*0.5)) ///
		xsize(5) ysize(5) yscale(titlegap(*4))

graph export I:\Workdata\706727\Figs\MentalServicesFigure_SeverityDep.eps , replace 
graph export I:\Workdata\706727\Figs\MentalServicesFigure_SeverityDep.png , replace width(2000)
 
 
/*********************/
/********* 3 *********/
/*********************/

/* RD-DID estimates */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

destring(kom),replace
merge m:1 kom year using  "I:\Workdata\706727\Build\Data\ChildhospByKomYear.dta" 
keep if _merge==3
drop _merge

* Same sample as year_collapse *
drop if year==2012 & month>3
keep if inrange(agec,15,23) 

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)
gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1

/* Convert to yearly rates */
foreach var in firstDbamb_AnxDep firstDerp_AnxDep firstDPHosp_AnxDep firstpois_painkiller {
replace `var'=`var'*100*12
}

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gen cutoff2006=cutoff if year==2006
bysort kom: egen max=max(cutoff2006)
replace cutoff2006=max
drop max

/* Regression */
gen belowcutoff=(agec<cutoff)

g byte above=(agec>=18) if !mi(agec)
g byte below=(agec<18) if !mi(agec)

g double dist=agec-18
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,2.5-abs(dist))

foreach var in firstDbamb_AnxDep firstDerp_AnxDep firstDPHosp_AnxDep firstpois_painkiller {

reg `var' 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff  1.Dyear#(1.above c.zabove c.zbelow)  [pw=kwt] if agec!=18 , vce(cluster pnr)

global est_RDDID_`var'=_b[1.Dyear#1.above]
global se_RDDID_`var'=_se[1.Dyear#1.above]

* Base level *
qui levelsof cutoff, local(lev)

	qui count if e(sample)==1
	local tot=r(N)
	
	global b_RDDID_`var'=_b[_cons]+_b[1.above]+_b[1.Dyear]
	foreach l of local lev {
	qui count if e(sample)==1 & cutoff==`l'
	local share=r(N)

		if (`l'<18) {
		global b_RDDID_`var'=${b_RDDID_`var'}+(`share'/`tot')*_b[`l'.cutoff]
		}
		if (`l'>18) {
		global b_RDDID_`var'=${b_RDDID_`var'}+(`share'/`tot')*(_b[`l'.cutoff]+_b[`l'.cutoff#1.belowcutoff])
		}
	}
}


/* Regression Discontinuity */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

* Same sample as year_collapse *
drop if year==2012 & month>3
keep if !inrange(agec,0,18) 

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)
gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1

/* Convert to yearly rates */
foreach var in firstDbamb_AnxDep firstDerp_AnxDep firstDPHosp_AnxDep firstpois_painkiller {
replace `var'=`var'*100*12
}
cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

keep if inrange(agec,20,58) & Dyear==1

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

foreach var in firstDbamb_AnxDep firstDerp_AnxDep firstDPHosp_AnxDep firstpois_painkiller {

qui reg `var' 1.above c.zabove c.zbelow   [pw=kwt] if Dyear==1 & agec!=38, vce(cluster pnr)

global est_RD_`var'=_b[1.above]
global b_RD_`var'=_b[_cons]
global se_RD_`var'=_se[1.above]
}

/* Create table */
clear

mat X=J(4,6,.)
mat stars=J(4,6,0)

local j=1
foreach met in RDDID RD  {
	
	local i=1
foreach var in firstDbamb_AnxDep firstDerp_AnxDep firstDPHosp_AnxDep firstpois_painkiller {
	
	di "`var'"
	di ${est_`met'_`var'}
	mat X[`i',`j']=${est_`met'_`var'}
	mat X[`i',`j'+1]=${b_`met'_`var'}
	mat X[`i',`j'+2]=${se_`met'_`var'}
	
	mat stars[`i',`j']=(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.645)+(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.96) + (abs(${est_`met'_`var'}/${se_`met'_`var'})>2.58)
	
	local i=`i'+1
	}
local j=`j'+3
}

frmttable using I:\workdata\706727\Figs\Final_FiguresAndTables_AdditionalMentalHealthTable.tex, tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,)) basefont(fs12) statfont(fs11) coljust(l c) ///
ctitle("Method","RDDID", "RD" \ "Age range", "18",  "37")   ///
sdec(3) ///
rtitle("Psyc. hosp. Outpat" \ " " \ " " \"Psyc. hosp. ER"  \" " \ " " \"Psyc. hosp. Inpat" \" " \ " " \"Poisoning with painkillers" \" " \ " " ) ///
multicol(1,2,2)

frmttable using I:\workdata\706727\Figs\Final_FiguresAndTables_AdditionalMentalHealthTable.rtf, replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,)) basefont(fs12) statfont(fs11)  coljust(l c) ///
ctitle("Method","RDDID", "RD" \ "Age range", "18",  "37")   ///
sdec(3) ///
rtitle("Psyc. hosp. Outpat" \ " " \ " " \"Psyc. hosp. ER"  \" " \ " " \"Psyc. hosp. Inpat" \" " \ " " \"Poisoning with painkillers" \" " \ " " ) ///
multicol(1,2,2)


/*********************/
/********* 4 *********/
/*********************/

/* RD-DID Estimates */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

destring(kom),replace
merge m:1 kom year using  "I:\Workdata\706727\Build\Data\ChildhospByKomYear.dta" 
keep if _merge==3
drop _merge

* Same sample as year_collapse *
drop if year==2012 & month>3
keep if inrange(agec,15,23) 

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gen cutoff2006=cutoff if year==2006
bysort kom: egen max=max(cutoff2006)
replace cutoff2006=max
drop max

/* Regression */
gen belowcutoff=(agec<cutoff)

g byte above=(agec>=18) if !mi(agec)
g byte below=(agec<18) if !mi(agec)

g double dist=agec-18
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,2.5-abs(dist))

foreach var in firstpsykhospAnxDep firstDbamb_AnxDep firstDerp_AnxDep firstDPHosp_AnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep  firstanxsleep  firstsui firstpois_painkiller {

qui ivregress 2sls `var' 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff 1.Dyear#c.zabove 1.Dyear#c.zbelow (firstpsyc=1.Dyear#1.above)  [pw=kwt] if  agec!=18, vce(cluster pnr)

global est_RDDID_`var'=_b[firstpsyc]
global se_RDDID_`var'=_se[firstpsyc]

}

/* Regression Discontinuity */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

* Same sample as year_collapse *
drop if year==2012 & month>3
keep if !inrange(agec,0,18) 

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

keep if inrange(agec,20,58) & Dyear==1

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

foreach var in  firstpsykhospAnxDep firstDbamb_AnxDep firstDerp_AnxDep firstDPHosp_AnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui firstpois_painkiller {

qui ivregress 2sls `var' c.zabove c.zbelow (firstpsyc = 1.above c.zabove c.zbelow) [pw=kwt] if  agec!=38, vce(cluster pnr)

global est_RD_`var'=_b[firstpsyc]
global se_RD_`var'=_se[firstpsyc]
}

/* Create table */
clear

mat X=J(11,4,.)
mat stars=J(11,4,0)

local j=1
foreach met in RDDID RD  {
	
	local i=1
foreach var in  firstpsykhospAnxDep firstDbamb_AnxDep firstDerp_AnxDep firstDPHosp_AnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui firstpois_painkiller  {
	
	mat X[`i',`j']=${est_`met'_`var'}
	mat X[`i',`j'+1]=${se_`met'_`var'}
	
	mat stars[`i',`j']=(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.645)+(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.96) + (abs(${est_`met'_`var'}/${se_`met'_`var'})>2.58)
	
	local i=`i'+1
	}
local j=`j'+2
}

frmttable using I:\workdata\706727\Figs\IVTable.tex, tex fragment replace statmat(X) sub(1) annotate(stars) asymbol(*,**,***) brackets("",""  \ (,)) basefont(fs12) statfont(fs11) coljust(l c) ///
ctitle("Method","RD-DID", "RD" \ "Age range", "18",  "37")   ///
sdec(3) ///
rtitle("Psychiatric hospital" \ " " \ "Psyc. hosp. Outpat" \ " " \ "Psyc. hosp. ER" \ " " \ "Psyc. hosp. Inpat" \ " " \"Psychiatrist"  \ " " \"PCP MHC" \ " " \"PCP Psych. test" \ " " \"Antidepressants" \ " " \"Anxiety and sleep meds." \ " "  \"Suicide Attempts" \ " " \"Poisoning w. painkiller" \ " " ) ///
multicol(1,2,2)

frmttable using I:\workdata\706727\Figs\IVTable.rtf, replace statmat(X) sub(1) annotate(stars) asymbol(*,**,***) brackets("",""  \ (,)) basefont(fs12) statfont(fs11)  coljust(l c) ///
ctitle("Method","RD-DID", "RD" \ "Age range", "18",  "37")   ///
sdec(3) ///
rtitle("Psychiatric hospital" \ " " \ "Psyc. hosp. Outpat" \ " " \ "Psyc. hosp. ER" \ " " \ "Psyc. hosp. Inpat" \ " " \"Psychiatrist"  \ " " \"PCP MHC" \ " " \"PCP Psych. test" \ " " \"Antidepressants" \ " " \"Anxiety and sleep meds." \ " "  \"Suicide Attempts" \ " " \"Poisoning w. painkiller" \ " " ) ///
multicol(1,2,2)


/*********************/
/********* 5 *********/
/*********************/

clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_final

keep if inrange(year,2000,2012)
drop if year==2012 & month>3
keep if inrange(agec,10,30) 

gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep

/* Estimates are not directly comparable to DID results */
foreach var in firstpsyc firsttherapy firstpsyk_test firstpsychiatry firstpsykhospAnxDep firstadep firstanxsleep firstsui firstpois_painkiller   {
replace `var'=`var'*100*12
}

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gcollapse (mean) firstpsyc firsttherapy firstpsyk_test firstpsychiatry firstpsykhospAnxDep firstadep firstanxsleep firstsui firstpois_painkiller , by(agec Dyear) fast

rename agec age
reshape long first , i(age Dyear) j(var) string
rename first koef


/** Appendix Figures **/
preserve
keep if inrange(age,10,26)

gen fita0=.
gen fita1=.
gen fitb0=.
gen fitb1=.
foreach var in psyc therapy psyk_test psychiatry psykhospAnxDep adep anxsleep sui pois_painkiller  {
	 
	foreach y in 0 1 {
		
	/* Fit local linear regressions */
	cap drop temp
	qui lpoly koef age   if age>18 &  age!=18 & Dyear==`y' & var=="`var'",  k(tri) nograph gen(temp) degree(1) at(age) bwidth(2.5) 
	qui replace fita`y'=temp if age>=18 & Dyear==`y' & var=="`var'"

	cap drop temp
	qui lpoly koef age   if age<18 &  age!=18 & Dyear==`y' & var=="`var'",  k(tri) nograph gen(temp) degree(1) at(age) bwidth(2.5) 
	qui replace fitb`y'=temp if age<=18 & Dyear==`y' & var=="`var'"
	}
} 
replace age=floor(age*2)/2
gcollapse (mean) koef fita0 fita1 fitb0 fitb1, by(age Dyear var)	fast

foreach var in psyc therapy psyk_test psychiatry psykhospAnxDep adep anxsleep sui pois_painkiller  {

twoway (scatter koef age if Dyear==0 & var=="`var'", mcolor(gs7) msymbol(circle_hollow)) (scatter koef age if Dyear==1 & var=="`var'", mcolor(red))  ///
		(line fitb0 age if Dyear==0 & var=="`var'" & age<=18, lcolor(gs7*1.4) lwidth(*1.5)) ///
		(line fita0 age if Dyear==0 & var=="`var'" & age>=18, lcolor(gs7*1.4) lwidth(*1.5))  ///
		(line fitb1 age if Dyear==1 & var=="`var'" & age<=18, lcolor(red*1.4) lwidth(*1.5)) ///
		(line fita1 age if Dyear==1 & var=="`var'" & age>=18, lcolor(red*1.4) lwidth(*1.5))  ///		
,graphregion(color(white)) xtitle("Age") scale(*1.1) ytitle("Percent") legend(order(2 "Post reform" 1 "Pre reform") rows(2) ring(0) region(color(white) margin(zero)) size(*0.9) pos(5)) xline(18) xlabel(10(2)26)  xsize(5) ysize(5)

graph export  "I:\workdata\706727\Figs\RDDID18_Figs_`var'.png", width(2000) replace
graph export  "I:\workdata\706727\Figs\RDDID18_Figs_`var'.eps", replace

}
restore


/*********************/
/********* 6 *********/
/*********************/

clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

/* Same data as collapse */
drop if year==2012 & month>3
keep if inrange(agec,20,58)

/* Generate variables */
cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1

/* Estimates are not directly comparable to DID results */
foreach var in firstpsyc firsttherapy firstpsyk_test firstpsychiatry firstpsykhospAnxDep firstDbamb_AnxDep firstDerp_AnxDep firstDPHosp_AnxDep firstadep firstanxsleep firstsui firstpois_painkiller {
replace `var'=`var'*100*12
}

/* Collapse data and create local linear trends */
gen weight=1
collapse (sum) weight (mean) firstpsyc firsttherapy firstpsyk_test firstpsychiatry firstpsykhospAnxDep firstDbamb_AnxDep ///
firstDerp_AnxDep firstDPHosp_AnxDep firstadep firstanxsleep firstsui firstpois_painkiller , by(agec Dyear) fast

foreach var in firstpsyc firsttherapy firstpsyk_test firstpsychiatry firstpsykhospAnxDep firstDbamb_AnxDep ///
firstDerp_AnxDep firstDPHosp_AnxDep firstadep firstanxsleep firstsui firstpois_painkiller {

preserve
cap drop fitb
qui lpoly `var' agec  [aw=weight] if agec>=38 & Dyear==1 & agec!=38,  k(tri) nograph gen(fitb) degree(1) at(agec) bwidth(7.5) 
qui replace fitb=. if agec<38

cap drop fita
qui lpoly `var' agec  [aw=weight] if agec<38 & Dyear==1 & agec!=38,  k(tri) nograph gen(fita) degree(1) at(agec) bwidth(7.5) 
qui replace fita=. if agec>38

replace agec=floor(agec*2)/2

collapse (mean) `var' fita fitb [aw=weight], by(agec Dyear) fast

twoway (scatter `var' agec if Dyear==1, mcolor(red) msize(small))  ///
	  (scatter `var' agec if Dyear==0, mcolor(gs7) msize(small) ms(circle_hollow)) ///
	  (line fita fitb agec if Dyear==1, lcolor(red*1.4 red*1.4) lwidth(*1.5 *1.5)) ///
	  ,xline(38, lcolor(red)) graphregion(color(white))  ///
	  legend(order(1 "Post reform" 2 "Pre reform" ) rows(2) pos(1) ring(0) region(color(white)) size(medlarge)) xtitle("Age", size(medlarge)) ytitle("Percent", size(medlarge)) ///
	  xscale(titlegap(*2)) yscale(titlegap(*6)) xsize(5) ysize(5) xlabel(,labsize(medlarge)) ylabel(,labsize(medlarge))
	  
graph export I:\workdata\706727\Figs\Final_Appendix_RD37_PrePost_`var'.png, width(2000) replace
graph export I:\workdata\706727\Figs\Final_Appendix_RD37_PrePost_`var'.eps,  replace

restore
}

/*********************/
/********* 7 *********/
/*********************/

/*** RD-DID estimates ***/
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

destring(kom),replace
merge m:1 kom year using  "I:\Workdata\706727\Build\Data\ChildhospByKomYear.dta" 
keep if _merge==3
drop _merge

* Same sample as year_collapse *
drop if year==2012 & month>3
keep if inrange(agec,15,23) 

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1

/* Estimates are not directly comparable to DID results */
foreach var in firstpsyc firstpsykhospAnxDep firstDbamb_AnxDep firstDerp_AnxDep firstDPHosp_AnxDep firstpsychiatry firsttherapy firstpsyk_test {
replace `var'=`var'*100*12
}

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gen cutoff2006=cutoff if year==2006
bysort kom: egen max=max(cutoff2006)
replace cutoff2006=max
drop max

/* Regression */
gen belowcutoff=(agec<cutoff)

g byte above=(agec>=18) if !mi(agec)
g byte below=(agec<18) if !mi(agec)

g double dist=agec-18
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,2.5-abs(dist))

/* Regression */
cap postclose john
postfile john d koef lower upper using "I:\Workdata\706727\Figs\Final_Appendix_RDDID_DifDiags", replace

forvalues d=0/9 {
cap drop firstpsykhosp_`d'
gen firstpsykhosp_`d'=firstpsykhosp*(bamb_1==`d' | bamb_2==`d' | erp_1==`d' | erp_2==`d' | st_phosp_1==`d' | st_phosp_2==`d')*100*12

qui reg firstpsykhosp_`d' 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff  1.Dyear#(1.above c.zabove c.zbelow)  [pw=kwt] if agec!=18 , vce(cluster pnr)

post john (`d') (_b[1.Dyear#1.above]) (_b[1.Dyear#1.above]-1.96*_se[1.Dyear#1.above]) (_b[1.Dyear#1.above]+1.96*_se[1.Dyear#1.above])

}
postclose john


/*** RD Estimate ***/
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_final

keep if inrange(year,2009,2011) | (year==2008 & month>=4) | (year==2012 & month<4)
keep if inrange(agec,20,58)

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

/* Regression */
cap postclose john
postfile john d koef lower upper using "I:\Workdata\706727\Figs\Final_Appendix_RD_DifDiags", replace

forvalues d=0/9 {
cap drop firstpsykhosp_`d'
gen firstpsykhosp_`d'=firstpsykhosp*(bamb_1==`d' | bamb_2==`d' | erp_1==`d' | erp_2==`d' | st_phosp_1==`d' | st_phosp_2==`d')*100*12

qui reg firstpsykhosp_`d' 1.above c.zabove c.zbelow   [pw=kwt] if agec!=38, vce(cluster pnr)
post john (`d') (_b[1.above]) (_b[1.above]-1.96*_se[1.above]) (_b[1.above]+1.96*_se[1.above])

}
postclose john

/* Create Figures */

* RDDID *
clear all
cd "I:\Workdata\706727\Figs"
use Final_Appendix_RDDID_DifDiags
		
label define john 0 "Organic 0" 1 "Substance use 1" 2 "Schizophrenia 2" 3 "Mood 3" 4 "Neurotic 4" 5 "Behavioral 5" 6 "Adult personality 6" 7 "Retardation 7" 8 "Psychosocial dev. 8" 9 "Beha. childhood 9"
label values d john 

twoway (rcap lower upper d, color(gs7)) (scatter koef d if d!=3 & d!=4, mcolor(black) mfcolor(white)) ///
		(scatter koef d if d==3 | d==4, mcolor(red)) , ///		
	    graphregion(color(white)) ylabel(-0.15(0.05)0.05) xsize(5) ysize(5) xtitle("ICD-10 Diagnosis Group") ytitle(Coefficient) xscale(titlegap(*6)) yscale(titlegap(*4)) ///
		legend(off) yline(0, lcolor(black)) xlabel(0(1)9,valuelabel angle(90)) xscale(titlegap(*2))

graph export I:\Workdata\706727\Figs\Final_Appendix_RDDID_DifDiags.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Appendix_RDDID_DifDiags.eps , replace 

* RD *
clear all
cd "I:\Workdata\706727\Figs"
use Final_Appendix_RD_DifDiags


label define john 0 "Organic 0" 1 "Substance use 1" 2 "Schizophrenia 2" 3 "Mood 3" 4 "Neurotic 4" 5 "Behavioral 5" 6 "Adult personality 6" 7 "Retardation 7" 8 "Psychosocial dev. 8" 9 "Beha. childhood 9"
label values d john 

twoway (rcap lower upper d, color(gs7)) (scatter koef d if d!=3 & d!=4, mcolor(black) mfcolor(white)) ///
		(scatter koef d if d==3 | d==4, mcolor(red)) , ///		
	    graphregion(color(white))  ylabel(-0.06(0.02)0.04) xsize(5) ysize(5) xtitle("ICD-10 Diagnosis Group") ytitle(Coefficient) xscale(titlegap(*6)) yscale(titlegap(*4)) ///
		legend(off) yline(0, lcolor(black)) xlabel(0(1)9,valuelabel angle(90))  xscale(titlegap(*2))

graph export I:\Workdata\706727\Figs\Final_Appendix_RD_DifDiags.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Appendix_RD_DifDiags.eps , replace 


/*********************/
/********* 8 *********/
/*********************/

clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)
drop if year==2012 & month>3

replace asui=0 if mi(asui)
replace psui=0 if mi(psui)
gen dsui=( c_liste49=="48")

gen john=(asui==1 | c_liste49=="48")
gcollapse (mean) asui psui dsui (sum) john, by(age) fast

keep if john>10
keep if inrange(age,15,60)
gen successful=dsui/(asui+dsui)

twoway (connect successful age) ///
, graphregion(color(white)) xtitle("Age") ytitle("Share")

graph export I:\Workdata\706727\Figs\Final_Appendix_SuiSuccess.eps , replace 
graph export I:\Workdata\706727\Figs\Final_Appendix_SuiSuccess.png , replace width(2000)


/*********************/
/********* 9 *********/
/*********************/

/*** RD-DID estimates ***/
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

destring(kom),replace
merge m:1 kom year using  "I:\Workdata\706727\Build\Data\ChildhospByKomYear.dta" 
keep if _merge==3
drop _merge

* Same sample as year_collapse *
drop if year==2012 & month>3
keep if inrange(agec,15,23) 

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1

local i=1
foreach var in firstadep firstssri firstanxiety firstsleep  {
gen prim_`var'=(substr(prescrib,`i',1)=="1") & `var'==1
gen phych_`var'=(substr(prescrib,`i',1)=="2") & `var'==1
gen sec_`var'=(substr(prescrib,`i',1)=="3") & `var'==1
local i=`i'+1
}

gen byte prim_firstanxsleep=(prim_firstanxiety==1 | prim_firstsleep==1)
gen byte phych_firstanxsleep=(phych_firstanxiety==1 | phych_firstsleep==1) & prim_firstanxsleep!=1
gen byte sec_firstanxsleep=(sec_firstanxiety==1 | sec_firstsleep==1) & prim_firstanxsleep!=1 & phych_firstanxsleep!=1

/* Estimates are not directly comparable to DID results */
foreach var in firstadep firstanxsleep prim_firstadep prim_firstanxsleep phych_firstadep phych_firstanxsleep sec_firstadep sec_firstanxsleep  {
replace `var'=`var'*100*12
}

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gen cutoff2006=cutoff if year==2006
bysort kom: egen max=max(cutoff2006)
replace cutoff2006=max
drop max

/* Regression */
gen belowcutoff=(agec<cutoff)

g byte above=(agec>=18) if !mi(agec)
g byte below=(agec<18) if !mi(agec)

g double dist=agec-18
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,2.5-abs(dist))

foreach var in firstadep firstanxsleep prim_firstadep prim_firstanxsleep phych_firstadep phych_firstanxsleep sec_firstadep sec_firstanxsleep  {
reg `var' 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff  1.Dyear#(1.above c.zabove c.zbelow)  [pw=kwt] if agec!=18 , vce(cluster pnr)

global est_RDDID_`var'=_b[1.Dyear#1.above]
global se_RDDID_`var'=_se[1.Dyear#1.above]

* Base level *
qui levelsof cutoff, local(lev)

	qui count if e(sample)==1
	local tot=r(N)
	
	global b_RDDID_`var'=_b[_cons]+_b[1.above]+_b[1.Dyear]
	foreach l of local lev {
	qui count if e(sample)==1 & cutoff==`l'
	local share=r(N)

		if (`l'<18) {
		global b_RDDID_`var'=${b_RDDID_`var'}+(`share'/`tot')*_b[`l'.cutoff]
		}
		if (`l'>18) {
		global b_RDDID_`var'=${b_RDDID_`var'}+(`share'/`tot')*(_b[`l'.cutoff]+_b[`l'.cutoff#1.belowcutoff])
		}
	}
}


/* Regression Discontinuity */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

local i=1
foreach var in firstadep firstssri firstanxiety firstsleep  {
gen prim_`var'=(substr(prescrib,`i',1)=="1") & `var'==1
gen phych_`var'=(substr(prescrib,`i',1)=="2") & `var'==1
gen sec_`var'=(substr(prescrib,`i',1)=="3") & `var'==1
local i=`i'+1
}

gen byte prim_firstanxsleep=(prim_firstanxiety==1 | prim_firstsleep==1)
gen byte phych_firstanxsleep=(phych_firstanxiety==1 | phych_firstsleep==1) & prim_firstanxsleep!=1
gen byte sec_firstanxsleep=(sec_firstanxiety==1 | sec_firstsleep==1) & prim_firstanxsleep!=1 & phych_firstanxsleep!=1


* Same sample as year_collapse *
drop if year==2012 & month>3
keep if !inrange(agec,0,18) 

/* Estimates are not directly comparable to DID results */
foreach var in  firstadep firstanxsleep   /// 
			    prim_firstadep prim_firstanxsleep   ///
			    phych_firstadep phych_firstanxsleep  ///
			    sec_firstadep sec_firstanxsleep  {
replace `var'=`var'*100*12
}

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

keep if inrange(agec,20,58) & Dyear==1

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

foreach var in  firstadep firstanxsleep   /// 
			    prim_firstadep prim_firstanxsleep   ///
			    phych_firstadep phych_firstanxsleep  ///
			    sec_firstadep sec_firstanxsleep  {
   
qui reg `var' 1.above c.zabove c.zbelow   [pw=kwt] if Dyear==1 & agec!=38, vce(cluster pnr)

global est_RD_`var'=_b[1.above]
global b_RD_`var'=_b[_cons]
global se_RD_`var'=_se[1.above]
}

/* Create table */

/* Full prescriber results */
clear

mat X=J(10,12,.)
mat stars=J(10,12,0)

local j=1
foreach met in RDDID RD  {
	
local i=1
	foreach var in  firstadep firstanxsleep  {
	local i=`i'+1
		foreach pre in "" "prim_" "phych_" "sec_" {
	   
		mat X[`i',`j']=${est_`met'_`pre'`var'}
		mat X[`i',`j'+1]=${b_`met'_`pre'`var'}
		mat X[`i',`j'+2]=${se_`met'_`pre'`var'}
		mat stars[`i',`j']=(abs(${est_`met'_`pre'`var'}/${se_`met'_`pre'`var'})>1.645)+(abs(${est_`met'_`pre'`var'}/${se_`met'_`pre'`var'})>1.96) + (abs(${est_`met'_`pre'`var'}/${se_`met'_`pre'`var'})>2.58)

		local i=`i'+1
		}
	}
local j=`j'+3
}

frmttable using I:\workdata\706727\Figs\Final_Appendix_ByPrescrib.tex, tex fragment replace statmat(X) sub(2) brackets("","" \ [,] \ (,)) annotate(stars) asymbol(*,**,***) basefont(fs12) statfont(fs11)  coljust(l c)  ///
ctitle("Method","RD-DID","RD" \ "Age range", "18", "37")   ///
sdec(3 ) ///
rtitle("\textbf{Antidepressants}" \"" \ "" \  "Total" \" " \ " " \  "PCP Prescriber" \" " \ " " \ "Psychiatrist Prescriber" \" " \ " " \ "Hospital Prescriber" \" " \ " " \  "\textbf{Anxiety meds}" \"" \ "" \  "Total" \" " \ " " \  "PCP Prescriber" \" " \ " " \ "Psychiatrist Prescriber" \" " \ " " \ "Hospital Prescriber" \" " \ " " ) ///
multicol(1,3,2)

frmttable using I:\workdata\706727\Figs\Final_Appendix_ByPrescrib.rtf, replace statmat(X) sub(2) brackets("","" \ [,] \ (,))  annotate(stars) asymbol(*,**,***) basefont(fs12) statfont(fs11)  coljust(l c) ///
ctitle("Method","RD-DID", "RD" \ "Age range", "18", "37")   ///
sdec(3 ) ///
rtitle("\textbf{Antidepressants}" \"" \ "" \  "Total" \" " \ " " \  "PCP Prescriber" \" " \ " " \ "Psychiatrist Prescriber" \" " \ " " \ "Hospital Prescriber" \" " \ " " \  "\textbf{Anxiety meds}" \"" \ "" \  "Total" \" " \ " " \  "PCP Prescriber" \" " \ " " \ "Psychiatrist Prescriber" \" " \ " " \ "Hospital Prescriber" \" " \ " " ) ///
multicol(1,3,2)

/*********************/
/********* 10 ********/
/*********************/

clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_final

gen yrm=year+(month-1)/12
keep if inrange(yrm,2000.25,2012.24)
keep if inrange(agec,10,26) 

destring(kom),replace
merge m:1 kom year using  "I:\Workdata\706727\Build\Data\ChildhospByKomYear.dta" 
keep if _merge==3
drop _merge

* Convert to yearly rates *
foreach var in  firstsui {
replace `var'=`var'*100*12
}

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

/* Regression */
gen belowcutoff=(agec<cutoff)

g byte above=(agec>=18) if !mi(agec)
g byte below=(agec<18) if !mi(agec)

g double dist=agec-18
g double zabove=above*dist
g double zbelow=dist

cap drop kwt
g double kwt=max(0,2.5-abs(dist))

* Pool years to increase precision *
cap drop year2
gen year2=2000 if inrange(yrm-0.25,2000,2001.99)
replace year2=2002 if inrange(yrm-0.25,2002,2003.99)
replace year2=2004 if inrange(yrm-0.25,2004,2005.99)
replace year2=2006 if inrange(yrm-0.25,2006,2007.99)
replace year2=2008 if inrange(yrm-0.25,2008,2009.99)
replace year2=2010 if inrange(yrm-0.25,2010,2011.99)


cap postclose john
postfile john str30 var year  koef lower upper using "I:\workdata\706727\Figs\RDDID18_ByYear_Figs", replace

foreach var in firstsui  {

reg `var' 1.above c.zabove c.zbelow ib2006.year2  i.cutoff#1.belowcutoff i.cutoff  ib2006.year2#(1.above c.zabove c.zbelow) [pw=kwt] if agec!=18 & !mi(year2), vce(cluster pnr)

	forvalues yr=2000(2)2010 {
	post john ("`var'") (`yr') (_b[`yr'.year2#1.above]) (_b[`yr'.year2#1.above]-1.96*_se[`yr'.year2#1.above]) (_b[`yr'.year2#1.above]+1.96*_se[`yr'.year2#1.above])

	}
}
postclose john


/** Create Figure **/
preserve
clear all
use "I:\workdata\706727\Figs\RDDID18_ByYear_Figs"

label define john 2000 "2000-2001" 2002 "2002-2003" 2004 "2004-2005" 2006 "2006-2007" 2008 "2008-2009" 2010 "2010-2011"
label values year john


foreach var in firstsui  {
    
twoway (connect koef year if var=="`var'", color(red)) (rcap lower upper year if var=="`var'", color(gs7)), ///
graphregion(color(white) margin(*7)) xtitle("") ytitle("Percentage points") legend(off) xline(2008, lcolor(black)) yline(0, lcolor(black)) ///
xlabel(,valuelabel) 

graph export  "I:\workdata\706727\Figs\RDDID18_ByYear_Figs_`var'.png", width(2000) replace
graph export  "I:\workdata\706727\Figs\RDDID18_ByYear_Figs_`var'.eps",  replace

}

restore

/*********************/
/********* 11 ********/
/*********************/

*** Figures ***

** RD-DID **
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(yrm,2000,2014)
keep if inrange(agec,15,25) 

/* Generate variables */
gen DpsykhospAnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firsterp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*DpsykhospAnxDep==1

sort pnr year month

cap drop cyear
gen cyear=year+(month-1)/12

foreach var in psyc psykhospAnxDep   {
	cap drop count`var'_0  
	gen byte count`var'_0=first`var'
	
	cap drop firstagain
	gen firstagain=0
	
	forvalues j=1(1)36 {	
	cap drop count`var'_`j'  
	replace firstagain=1 if (first`var'==1 & first`var'[_n+`j']==1) & (pnr==pnr[_n+`j'] & cyear[_n+`j']-cyear<=3) 
	by pnr: gen byte count`var'_`j'=(first`var'==1 & firstagain==0)*D`var'[_n+`j'] if  (pnr==pnr[_n+`j'] & cyear[_n+`j']-cyear<=3)	
	}
}

keep if inrange(agec,15,23) & inrange(yrm,2000,2012.25)
keep pnr year month agec kom count* 

destring(kom),replace
merge m:1 kom year using  "I:\Workdata\706727\Build\Data\ChildhospByKomYear.dta" 
keep if _merge==3
drop _merge

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gen cutoff2006=cutoff if year==2006
bysort kom: egen max=max(cutoff2006)
replace cutoff2006=max
drop max

/* Regression */
gen belowcutoff=(agec<cutoff)

g byte above=(agec>=18) if !mi(agec)
g byte below=(agec<18) if !mi(agec)

g double dist=agec-18
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,2.5-abs(dist))

cap postclose john
postfile john str30 var dist koef lower upper base using "I:\Workdata\706727\Figs\RDDID_LongRun", replace

foreach var in psyc psykhospAnxDep  {
	
	forvalues j=0(1)36 {	
	qui reg count`var'_`j' 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff  1.Dyear#(1.above c.zabove c.zbelow)  [pw=kwt] if agec!=18 , vce(cluster pnr)

	post john ("`var'") (`j') (_b[1.Dyear#1.above]) (_b[1.Dyear#1.above]-1.96*_se[1.Dyear#1.above]) (_b[1.Dyear#1.above]+1.96*_se[1.Dyear#1.above]) (_b[_cons]+_b[1.Dyear]+_b[1.above])
	}
}
postclose john

** RD **
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(yrm,2008.25,2014)
keep if !inrange(agec,0,30) 

/* Generate variables */
gen DpsykhospAnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firsterp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*DpsykhospAnxDep==1

sort pnr year month

cap drop cyear
gen cyear=year+(month-1)/12

foreach var in psyc psykhospAnxDep   {
	cap drop count`var'_0  
	gen byte count`var'_0=first`var'
	
	cap drop firstagain
	gen firstagain=0
	
	forvalues j=1(1)36 {	
	cap drop count`var'_`j'  
	replace firstagain=1 if (first`var'==1 & first`var'[_n+`j']==1) & (pnr==pnr[_n+`j'] & cyear[_n+`j']-cyear<=3) 
	by pnr: gen byte count`var'_`j'=(first`var'==1 & firstagain==0)*D`var'[_n+`j'] if  (pnr==pnr[_n+`j'] & cyear[_n+`j']-cyear<=3)	
	}
}

keep if inrange(agec,30,48) & inrange(yrm,2008.25,2012.25)
keep pnr year month agec count* 

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

cap postclose john
postfile john str30 var dist koef lower upper base using "I:\Workdata\706727\Figs\RD_LongRun", replace

foreach var in psyc psykhospAnxDep  {
	
	forvalues j=0(1)36 {	
	qui reg  count`var'_`j' 1.above c.zabove c.zbelow [pw=kwt] if  agec!=38, vce(cluster pnr) 
	post john ("`var'") (`j') (_b[1.above]) (_b[1.above]-1.96*_se[1.above]) (_b[1.above]+1.96*_se[1.above]) (_b[_cons])
	}
}
postclose john


/** Main Text graph **/
clear all
cd "I:\Workdata\706727\Figs"
use RDDID_LongRun

gen meth="RDDID"
append using RD_LongRun
replace  meth="RD" if mi(meth)

sort meth var dist

** Change to yearly rates and percent **
foreach out in koef lower upper {
replace `out'=`out'*100*12 
}

twoway  (rcap lower upper dist if var=="psyc" & meth=="RDDID", color(eltblue*1.5)) (connect koef dist if var=="psyc" & meth=="RDDID", color(eltblue*1.5) ms(T) msize(*1.2))  ///
		(rcap lower upper dist if var=="psyc" & meth=="RD", color(green*0.8)) (connect koef dist if var=="psyc" & meth=="RD", color(green*0.8) msize(*1.2))  ///
, graphregion(color(white)) xtitle("Distance (months)", size(medlarge)) ytitle("Percentage points", size(medlarge)) title("Psychologist", color(black)) yline(0,lcolor(black)) ///
legend(order(2 "RD-DID 18" 4 "RD 37") rows(2) ring(0) pos(3) region(color(white)) size(medlarge)) name(psyc,replace)  xlabel(0(12)36, labsize(medlarge)) ylabel(,labsize(medlarge)) ///
yscale(titlegap(*3)) xscale(titlegap(*3))

twoway  (rcap lower upper dist if var=="psykhospAnxDep" & meth=="RDDID" & dist!=0, color(eltblue*1.2)) (connect koef dist if var=="psykhospAnxDep" & meth=="RDDID", color(eltblue*1.2) ms(T) msize(*1.2))  ///
		(rcap lower upper dist if var=="psykhospAnxDep" & meth=="RD", color(green*0.8)) (connect koef dist if var=="psykhospAnxDep" & meth=="RD", color(green*0.8) msize(*1.2))  ///
, graphregion(color(white)) xtitle("Distance (months)", size(medlarge)) ytitle("Percentage points",size(medlarge)) title("Psychiatric hospital", color(black) size(large)) yline(0,lcolor(black)) ///
legend(order(2 "RD-DID 18" 4  "RD 37") rows(2) ring(0) pos(5) region(color(white)) size(medlarge)) name(psykhospAnxDep,replace) xlabel(0(12)36, labsize(medlarge)) ylabel(-0.1(0.05)0.05,labsize(medlarge)) yscale(titlegap(*3)) xscale(titlegap(*3))

graph combine psyc psykhospAnxDep , iscale(*1.5) graphregion(color(white)) xsize(15) ysize(5)

graph export "I:\Workdata\706727\Figs\Final_MH_LongRun.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\Final_MH_LongRun.eps", replace 



*** Table ***
** RD - DID **
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(yrm,2000,2014)
keep if inrange(agec,15,25) 

/* Generate variables */
gen DpsykhospAnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firsterp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*DpsykhospAnxDep==1

sort pnr year month

cap drop cyear
gen cyear=year+(month-1)/12

foreach var in psyc psykhospAnxDep   {
	cap drop count`var'_0  
	gen byte count`var'_0=first`var'
	
	cap drop firstagain
	gen firstagain=0
	
	forvalues j=1(1)36 {	
	cap drop count`var'_`j'  
	replace firstagain=1 if (first`var'==1 & first`var'[_n+`j']==1) & (pnr==pnr[_n+`j'] & cyear[_n+`j']-cyear<=3) 
	by pnr: gen byte count`var'_`j'=(first`var'==1 & firstagain==0)*D`var'[_n+`j'] if  (pnr==pnr[_n+`j'] & cyear[_n+`j']-cyear<=3)	
	}
}

keep if inrange(agec,15,23) & inrange(yrm,2000,2012.25)
keep pnr year month agec kom count* 

destring(kom),replace
merge m:1 kom year using  "I:\Workdata\706727\Build\Data\ChildhospByKomYear.dta" 
keep if _merge==3
drop _merge

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gen cutoff2006=cutoff if year==2006
bysort kom: egen max=max(cutoff2006)
replace cutoff2006=max
drop max

/* Regression */
gen belowcutoff=(agec<cutoff)

g byte above=(agec>=18) if !mi(agec)
g byte below=(agec<18) if !mi(agec)

g double dist=agec-18
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,2.5-abs(dist))

cap postclose john
postfile john str30 var dist koef lower upper base using "I:\Workdata\706727\Figs\RDDID_LongRun", replace

foreach var in psyc psykhospAnxDep  {
	
	forvalues j=0(1)36 {	
	qui reg count`var'_`j' 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff  1.Dyear#(1.above c.zabove c.zbelow)  [pw=kwt] if agec!=18 , vce(cluster pnr)

	post john ("`var'") (`j') (_b[1.Dyear#1.above]) (_b[1.Dyear#1.above]-1.96*_se[1.Dyear#1.above]) (_b[1.Dyear#1.above]+1.96*_se[1.Dyear#1.above]) (_b[_cons]+_b[1.Dyear]+_b[1.above])
	}
}
postclose john

** RD **
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(yrm,2008.25,2014)
keep if !inrange(agec,0,30) 

/* Generate variables */
gen DpsykhospAnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firsterp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*DpsykhospAnxDep==1

sort pnr year month

cap drop cyear
gen cyear=year+(month-1)/12

foreach var in psyc psykhospAnxDep   {
	cap drop count`var'_0  
	gen byte count`var'_0=first`var'
	
	cap drop firstagain
	gen firstagain=0
	
	forvalues j=1(1)36 {	
	cap drop count`var'_`j'  
	replace firstagain=1 if (first`var'==1 & first`var'[_n+`j']==1) & (pnr==pnr[_n+`j'] & cyear[_n+`j']-cyear<=3) 
	by pnr: gen byte count`var'_`j'=(first`var'==1 & firstagain==0)*D`var'[_n+`j'] if  (pnr==pnr[_n+`j'] & cyear[_n+`j']-cyear<=3)	
	}
}

keep if inrange(agec,30,48) & inrange(yrm,2008.25,2012.25)
keep pnr year month agec count* 

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

cap postclose john
postfile john str30 var dist koef lower upper base using "I:\Workdata\706727\Figs\RD_LongRun", replace

foreach var in psyc psykhospAnxDep  {
	
	forvalues j=0(1)36 {	
	qui reg  count`var'_`j' 1.above c.zabove c.zbelow [pw=kwt] if  agec!=38, vce(cluster pnr) 
	post john ("`var'") (`j') (_b[1.above]) (_b[1.above]-1.96*_se[1.above]) (_b[1.above]+1.96*_se[1.above]) (_b[_cons])
	}
}
postclose john

/** Create graph **/
clear all
cd "I:\Workdata\706727\Figs"
use RDDID_LongRun

gen meth="RDDID"
append using RD_LongRun
replace  meth="RD" if mi(meth)

sort meth var dist

** Change to yearly rates and percent **
foreach out in koef lower upper {
replace `out'=`out'*100*12 
}

twoway  (rcap lower upper dist if var=="psyc" & meth=="RDDID", color(eltblue*1.5)) (connect koef dist if var=="psyc" & meth=="RDDID", color(eltblue*1.5) ms(T) msize(*1.2))  ///
		(rcap lower upper dist if var=="psyc" & meth=="RD", color(green*0.8)) (connect koef dist if var=="psyc" & meth=="RD", color(green*0.8) msize(*1.2))  ///
, graphregion(color(white)) xtitle("Distance (months)", size(medlarge)) ytitle("Percentage points", size(medlarge)) title("Psychologist", color(black)) yline(0,lcolor(black)) ///
legend(order(2 "RD-DID 18" 4 "RD 37") rows(2) ring(0) pos(3) region(color(white)) size(medlarge)) name(psyc,replace)  xlabel(0(12)36, labsize(medlarge)) ylabel(,labsize(medlarge)) ///
yscale(titlegap(*3)) xscale(titlegap(*3))

twoway  (rcap lower upper dist if var=="psykhospAnxDep" & meth=="RDDID" & dist!=0, color(eltblue*1.2)) (connect koef dist if var=="psykhospAnxDep" & meth=="RDDID", color(eltblue*1.2) ms(T) msize(*1.2))  ///
		(rcap lower upper dist if var=="psykhospAnxDep" & meth=="RD", color(green*0.8)) (connect koef dist if var=="psykhospAnxDep" & meth=="RD", color(green*0.8) msize(*1.2))  ///
, graphregion(color(white)) xtitle("Distance (months)", size(medlarge)) ytitle("Percentage points",size(medlarge)) title("Psychiatric hospital", color(black) size(large)) yline(0,lcolor(black)) ///
legend(order(2 "RD-DID 18" 4  "RD 37") rows(2) ring(0) pos(5) region(color(white)) size(medlarge)) name(psykhospAnxDep,replace) xlabel(0(12)36, labsize(medlarge)) ylabel(-0.1(0.05)0.05,labsize(medlarge)) yscale(titlegap(*3)) xscale(titlegap(*3))

graph combine psyc psykhospAnxDep , iscale(*1.5) graphregion(color(white)) xsize(15) ysize(5)

graph export "I:\Workdata\706727\Figs\Final_MH_LongRun.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\Final_MH_LongRun.eps", replace 


/*********************/
/********* 12 ********/
/*********************/

/**** RD-in-Time Estimates ****/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,21,27.99)
keep if inrange(distyrm,-3.5,7)

keep pnr dupli distyrm treatagec tyrm yrm agec firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp

drop if agec<=18

** drop individuals just before cutoff ** 
drop if inrange(tyrm,2008,2008.24)

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
gen tyrm2=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm2


keep if inrange(distyrm,-2.75,7)
gcollapse (mean) firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp, by(pnr pnrg distyrm treatagec tyrm yrm) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen distg=group(distyrm)
egen yrmg=group(yrm)

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=3
global base=r(max)-${bdist}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

compress

** Load slightly different version of areg (only appropriate when clusters nest absorb variable) **
cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

cap postclose john
postfile john str30 var dist treat koef lower upper base using "I:\workdata\706727\Figs\PsykTestLongRunRD_EventGraph_Labor_RDtime", replace

foreach var in  Ddisab Dsick Dsueduc Dallnonparleave emp  {

qui reg `var' 1.above c.zabove c.zbelow [pw=kwt] if tyrm!=2008.25 & distg==${base}
global cons=_b[_cons]+_b[1.above]

qui aregben `var' i.yrmg ib${maxm1}.bgdistg ib${maxm1}.bgdistg#c.zbelow ib${maxm1}.bgdistg#c.zabove ib${maxm1}.bgdistg#1.above [pw=kwt] ,  absorb(pnrg) vce(cluster pnr)

local dmax=${max}
local dmin=${base}+${bdist}

mat V=e(V)
mat b=e(b)

	forvalues d=1/`dmax' {

	global cont=_b[`d'.bgdistg]
	global secont=_se[`d'.bgdistg]
	global treat=_b[`d'.bgdistg#1.above]+_b[`d'.bgdistg]
	global setreat=sqrt(V["`d'.bgdistg#1.above","`d'.bgdistg#1.above"]+V["`d'.bgdistg","`d'.bgdistg"]+2*V["`d'.bgdistg#1.above","`d'.bgdistg"])
	
	
	post john ("`var'") (`d') (0) (${cont}) (${cont}-1.96*${secont}) (${cont}+1.96*${secont}) (${cons})
	post john ("`var'") (`d') (1) (${treat}) (${treat}-1.96*${setreat}) (${treat}+1.96*${setreat}) (${cons})
	post john ("`var'")  (`d') (2) (_b[`d'.bgdistg#1.above]) (_b[`d'.bgdistg#1.above]-1.96*_se[`d'.bgdistg#1.above]) (_b[`d'.bgdistg#1.above]+1.96*_se[`d'.bgdistg#1.above]) (${cons})
	}
}

postclose john

/***** RD *****/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(tyrm,2008.25,2012.25)
keep if inrange(treatagec,28,48)
keep if inrange(distyrm,-5,7)

keep pnr dupli distyrm treatagec tyrm yrm agec firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
gen tyrm2=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm2

gcollapse (mean) firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp, by(pnr pnrg distyrm treatagec tyrm yrm) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

egen distg=group(distyrm)
egen yrmg=group(yrm)

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=6
global base=r(max)-${bdist}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

** Load slightly different version of areg (only appropriate when clusters nest absorb variable) **
cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

cap postclose john
postfile john str30 var dist treat koef lower upper base using "I:\workdata\706727\Figs\PsykTestLongRunRD_EventGraph_Labor_RD", replace

local dmax=${max}
local dmin=${base}+${bdist}

foreach var in  Ddisab Dsick Dallnonparleave emp {

qui reg `var' 1.above c.zabove c.zbelow [pw=kwt] if treatage!=38 & distg==${base}
global cons=_b[_cons]+_b[1.above]

qui aregben `var' ibn.yrmg  ib${maxm1}.bgdistg ib${maxm1}.bgdistg#(c.zabove c.zbelow) ib${maxm1}.bgdistg#1.above [pw=kwt] if treatage!=38 ,vce(cluster pnr) absorb(pnrg)
 
mat V=e(V)
mat b=e(b)

	forvalues d=1/`dmax' {

	global cont=_b[`d'.bgdistg]
	global secont=_se[`d'.bgdistg]
	global treat=_b[`d'.bgdistg#1.above]+_b[`d'.bgdistg]
	global setreat=sqrt(V["`d'.bgdistg#1.above","`d'.bgdistg#1.above"]+V["`d'.bgdistg","`d'.bgdistg"]+2*V["`d'.bgdistg#1.above","`d'.bgdistg"])
	
	post john ("`var'") (`d') (0) (${cont}) (${cont}-1.96*${secont}) (${cont}+1.96*${secont}) (${cons})
	post john ("`var'") (`d') (1) (${treat}) (${treat}-1.96*${setreat}) (${treat}+1.96*${setreat}) (${cons})
	}
}
postclose john


/** Create Figures **/

clear all
cd "I:\Workdata\706727\Figs"
use PsykTestLongRunRD_EventGraph_Labor_RDtime

gen ageg=1
gen meth="RDtime"

append using PsykTestLongRunRD_EventGraph_Labor_RD
replace meth="RD" if mi(meth)
replace ageg=2 if mi(ageg)

/* Convert to percentage points */
foreach var in koef lower upper base {
replace `var'=`var'*100
}

gen olddist=dist
replace dist=15 if olddist==49  & ageg!=1
replace dist=49 if olddist==15  & ageg!=1
replace dist=1 if olddist==48   & ageg!=1
replace dist=48 if olddist==1   & ageg!=1

replace dist=9 if olddist==40  & ageg==1
replace dist=40 if olddist==9  & ageg==1
replace dist=1 if olddist==39   & ageg==1
replace dist=39 if olddist==1   & ageg==1

sort var dist 

replace dist=(dist-21)/4 if  ageg!=1
replace dist=(dist-12)/4 if  ageg==1

foreach var in Dsick Ddisab Dallnonparleave emp {
if ("`var'"=="Dsick") {
local tit2 "Sickness benefits"
local tp=7.5
local ylab1 "-5(5)20"
local ylab2 "-5(5)20"
local pos=1
}
if ("`var'"=="Ddisab") {
local tit2 "Disability pension"
local tp=4
local ylab1 "-2(2)10"
local ylab2 "-2(2)10"
local pos=11
}
if ("`var'"=="Dallnonparleave") {
local tit2 "Any labor market transfer"
local tp=10
local ylab1 "-15(15)30"
local ylab2 "-10(10)20"
local pos=1
}
if ("`var'"=="emp") {
local tit2 "Employment"
local tp=-14
local ylab1 "-40(10)20"
local ylab2 "-15(5)10"
local pos=1
}

if ("`var'"=="Dsick" | "`var'"=="Dallnonparleave" ) {
local ttit1 "ES-RD-Time: Age 21-27"	
local ttit2 "ES-RD: Age 37"
}
if ("`var'"!="Dsick" & "`var'"!="Dallnonparleave" ) {
local ttit1 ""	
local ttit2 ""	
}
if ("`var'"=="Ddisab" | "`var'"=="emp" ) {
local xops `"xlabel(-5(1)7,labsize(medium)) xscale(titlegap(*3)) xtitle("Years from mental health shock",size(medium))"'
}
if ("`var'"!="Ddisab" & "`var'"!="emp" ) {
local xops "xlabel(-5(1)7,labsize(medium)) xscale(titlegap(*3)) xtitle("")"
}

	forvalues ageg=1/2 {

	if (`ageg'==1) {
	local yops `"ytitle("Percentage points",size(medium))"'
	}
	if (`ageg'!=1) {
	local yops `"ytitle("")"'
	}	
	
	sum base if var=="`var'" & ageg==`ageg'
	global  dibase: di %10.1f r(mean)

	twoway 	(rcap lower upper dist if var=="`var'"  & treat==0 & ageg==`ageg', color(black))  ///
			(rcap lower upper dist if var=="`var'"  & treat==1 & ageg==`ageg', color(red))  ///
			(line koef dist if var=="`var'"  & treat==0 & ageg==`ageg', lcolor(black))  ///
			(line koef dist if var=="`var'"  & treat==1 & ageg==`ageg', lcolor(red) ) ///
			,graphregion(color(white) margin(small)) `xops' `yops' ///
	legend(order(4 "Treatment" 3 "Control") rows(2) ring(0) pos(`pos') region(color(white) margin(small)) symxsize(small) size(medium) rowgap(*0.5)) ///
	title("`ttit`ageg''", color(black) size(medium)) nodraw text(`tp' -2.75 "Baseline:""${dibase}" , box lcolor(white) fcolor(white)) ///
	xlabel(-5(1)7,labsize(medium)) ylabel(`ylab`ageg'',labsize(medium)) xscale(titlegap(*4)) yscale(titlegap(*4)) xsize(5) ysize(4) xline(0, lcolor(black)) name(plot`ageg', replace)

	}

graph combine plot1 plot2 , iscale(*0.8) graphregion(color(white) margin(zero)) title("`tit2'", color(black) size(small)) name(`var', replace)  rows(1)

}

/* Fig 1 */
graph combine Dsick Ddisab, iscale(*1.1) graphregion(color(white) margin(small))  rows(3) xsize(18) ysize(20)

graph export "I:\Workdata\706727\Figs\PsykTestLongRunRD_Final_Labor_Appendix_ByAge_1.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\PsykTestLongRunRD_Final_Labor_Appendix_ByAge_1.eps", replace 

/* Fig 2 */
graph combine Dallnonparleave emp, iscale(*1.1) graphregion(color(white) margin(small))  rows(3) xsize(18) ysize(20)

graph export "I:\Workdata\706727\Figs\PsykTestLongRunRD_Final_Labor_Appendix_ByAge_2.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\PsykTestLongRunRD_Final_Labor_Appendix_ByAge_2.eps", replace 

/**** Education ***/
sum base if var=="Dsueduc" & ageg==1
global  dibase: di %10.1f r(mean)

twoway 	(rcap lower upper dist if var=="Dsueduc"  & treat==0 & meth=="RDtime", color(black))  ///
		(rcap lower upper dist if var=="Dsueduc"  & treat==1 & meth=="RDtime", color(red))  ///
		(line koef dist if var=="Dsueduc"  & treat==0 & meth=="RDtime", color(black) mfcolor(white))  ///
		(line koef dist if var=="Dsueduc"  & treat==1 & meth=="RDtime", color(red) ) ///
		,graphregion(color(white)) xlabel(-5(1)7,labsize(medlarge)) xscale(titlegap(*4)) xtitle("Years from mental health shock",size(medium)) ytitle("Percentage points",size(medlarge)) ///
title("Education stipends"" ", color(black) size(large)) t2title("ES-RD-Time: Age 21-27", color(black) size(medlarge)) text(15 -2.75 "Baseline:${dibase}" , box lcolor(white) fcolor(white)) ///
legend(order(4 "Treatment" 3 "Control") rows(2) ring(0) pos(11) region(color(white) margin(small)) symxsize(small) size(medium) rowgap(*0.5)) ///
 xscale(titlegap(*4)) ylabel(,labsize(none)) yscale(titlegap(*4)) xsize(5) ysize(4) xline(0, lcolor(black)) 

graph export "I:\Workdata\706727\Figs\PsykTestLongRunRD_Final_Labor_Appendix_ByAge_Educ.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\PsykTestLongRunRD_Final_Labor_Appendix_ByAge_Educ.eps", replace 


/*********************/
/********* 13 ********/
/*********************/

/*** Bootstrap standard errors for RD-in-Time model ***/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,21,27.99)
keep if inrange(distyrm,-6,7)

keep pnr dupli distyrm treatagec tyrm yrm year agec firstpsyc inc earn 

** drop individuals just before cutoff ** 
drop if inrange(tyrm,2008,2008.25)

/* DEFLATE VARIABLES */
cap program drop deflat
do "I:\Workdata\706727\STATA Programs\deflat.do"
deflat earn 1 year 2020
deflat inc 1 year 2020

** Winsorize **
replace inc=0 if inc<0
replace earn=0 if earn<0
foreach var in  inc earn  {
sum `var' ,d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
replace `var'=r(p1) if `var'<r(p1) & !mi(`var') & r(p1)<0
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm)
gen tyrm2=floor(tyrm)
cap drop distyrm*
gen distyrm=yrm-tyrm2

keep if inrange(distyrm,-5,7)
gcollapse (mean) firstpsyc inc earn, by(pnr pnrg distyrm treatagec tyrm yrm) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen distg=group(distyrm)

/** Create postshock dummies **/
sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

egen yrmg=group(yrm)

sum distg if distyrm
global max=r(max)
global maxm1=r(max)-1

gen treatinyear=round((tyrm-floor(tyrm))*4)
gen misyear=treatinyear/4


** Load slightly different version of areg (only appropriate when clusters nest absorb variable) **
cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

keep pnr pnrg yrmg firstpsyc inc earn zabove zbelow above bgdistg distgpoolpre misyear kwt

cap postclose john 
postfile john it  str30 var dist koef  using "I:\workdata\706727\Figs\App_YearlyLaborRDtimeBootstrap", replace

forvalues it=1/100 {
preserve
set seed `it'
bsample , cluster(pnr) 
	
	foreach var in firstpsyc inc earn   {
		
	qui aregben `var' i.yrmg i.bgdistg#c.misyear i.bgdistg#c.zabove#c.misyear i.bgdistg#c.zbelow#c.misyear ib${base}.distgpoolpre#1.above#c.misyear i.bgdistg i.bgdistg#c.zabove i.bgdistg#c.zbelow ib${base}.distgpoolpre#1.above [pw=kwt], absorb(pnrg) 
	
		forvalues y=5/12 {
		post john (`it')  ("`var'") (`y') (_b[`y'.distgpoolpre#1.above])
		}
	}	
	
di `it'

restore
}
postclose john


/**** RD-in-time ****/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,21,27.99)
keep if inrange(distyrm,-6,7)

keep pnr dupli distyrm treatagec tyrm yrm year agec firstpsyc inc earn 

** drop individuals just before cutoff ** 
drop if inrange(tyrm,2008,2008.25)

/* DEFLATE VARIABLES */
cap program drop deflat
do "I:\Workdata\706727\STATA Programs\deflat.do"
deflat earn 1 year 2020
deflat inc 1 year 2020

** Winsorize **
replace inc=0 if inc<0
replace earn=0 if earn<0
foreach var in  inc earn  {
sum `var' ,d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
replace `var'=r(p1) if `var'<r(p1) & !mi(`var') & r(p1)<0
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm)
gen tyrm2=floor(tyrm)
cap drop distyrm*
gen distyrm=yrm-tyrm2

keep if inrange(distyrm,-5,7)
gcollapse (mean) firstpsyc inc earn, by(pnr pnrg distyrm treatagec tyrm yrm) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen distg=group(distyrm)

/** Create postshock dummies **/
sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

egen yrmg=group(yrm)

sum distg if distyrm
global max=r(max)
global maxm1=r(max)-1

gen treatinyear=round((tyrm-floor(tyrm))*4)
gen misyear=treatinyear/4

* Standard errors *
preserve
clear 
use "I:\Workdata\706727\Figs\App_YearlyLaborRDtimeBootstrap"

bysort it var: egen sumkoef=sum(koef)
bysort it var: egen temp=sum(koef) if dist==6 | dist==7 
bysort it var: egen sumkoef2=max(temp)

keep it var sumkoef sumkoef2
duplicates drop

gen temp=sumkoef*12 if var=="firstpsyc"
bysort it: egen firststage=max(temp)

cap drop temp
gen temp=sumkoef2*12 if var=="firstpsyc"
bysort it: egen firststage2=max(temp)
	
gen secondstage=sumkoef/firststage
gen secondstage2=sumkoef2/firststage2

sum sumkoef if  var=="firstpsyc"
global sefirstpsyc=r(sd)

sum sumkoef2 if  var=="firstpsyc"
global sefirstpsyc2=r(sd)

* Second stage *
foreach var in inc earn   {

sum secondstage if var=="`var'"
global se_RDtime_`var'=r(sd)

sum secondstage2 if var=="`var'"
global se_RDtime2_`var'=r(sd)
}
restore

** Load slightly different version of areg (only appropriate when clusters nest absorb variable) **
cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

keep pnr pnrg yrmg firstpsyc inc earn zabove zbelow above bgdistg distgpoolpre misyear kwt

* First stage 
qui aregben firstpsyc i.yrmg i.bgdistg#c.misyear i.bgdistg#c.zabove#c.misyear i.bgdistg#c.zbelow#c.misyear ib${base}.distgpoolpre#1.above#c.misyear i.bgdistg i.bgdistg#c.zabove i.bgdistg#c.zbelow ib${base}.distgpoolpre#1.above [pw=kwt], absorb(pnrg) 
global firststage=0
global firststage2=0
forvalues y=5/12 {
global firststage=${firststage} + _b[`y'.distgpoolpre#1.above]*12
	if (`y'<8) {
	global firststage2=${firststage2} + _b[`y'.distgpoolpre#1.above]*12
	}
}

* Baseline
foreach var in inc earn {
		
reg `var' c.zbelow c.zabove 1.above c.misyear c.zbelow#c.misyear c.zabove#c.misyear 1.above#c.misyear i.distg#c.misyear i.distg#c.zabove#c.misyear i.distg#c.zbelow#c.misyear ib${base}.distg#1.above#c.misyear ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${base}.distg#1.above [pw=kwt]

global b_RDtime_`var'=0
global b_RDtime2_`var'=0

	forvalues y=5/13 {
	global b_RDtime_`var'=${b_RDtime_`var'} +(_b[_cons]+_b[`y'.distg])	
			if (`y'<8) {
			global b_RDtime2_`var'=${b_RDtime2_`var'} +(_b[_cons]+_b[`y'.distg])
			}
	}
}

* Estimates
foreach var in inc earn   {
	
qui aregben `var' i.yrmg i.bgdistg#c.misyear i.bgdistg#c.zabove#c.misyear i.bgdistg#c.zbelow#c.misyear ib${base}.distgpoolpre#1.above#c.misyear i.bgdistg i.bgdistg#c.zabove i.bgdistg#c.zbelow ib${base}.distgpoolpre#1.above [pw=kwt], absorb(pnrg) 


global est_RDtime_`var'=0
global est_RDtime2_`var'=0
	forvalues y=5/13 {
	global est_RDtime_`var'=${est_RDtime_`var'} +_b[`y'.distgpoolpre#1.above]/${firststage}	
			if (`y'<8) {
			global est_RDtime2_`var'=${est_RDtime2_`var'} +_b[`y'.distgpoolpre#1.above]/${firststage2}
			}
	}

}

/***** RD *******/
clear 
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(tyrm,2008.25,2012.25)
keep if inrange(treatagec,30,47)
keep if inrange(distyrm,-6,7)

keep pnr dupli distyrm treatagec tyrm yrm year agec firstpsyc inc earn   

/* DEFLATE VARIABLES */
cap program drop deflat
do "I:\Workdata\706727\STATA Programs\deflat.do"
deflat earn 1 year 2020
deflat inc 1 year 2020

** Winsorize **
replace inc=0 if inc<0
replace earn=0 if earn<0
foreach var in  inc earn  {
sum `var' ,d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
replace `var'=r(p1) if `var'<r(p1) & !mi(`var') & r(p1)<0
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm)
gen tyrm2=floor(tyrm)
cap drop distyrm*
gen distyrm=yrm-tyrm2

keep if inrange(distyrm,-5,7)
gcollapse (mean) firstpsyc inc earn , by(pnr pnrg distyrm treatagec tyrm yrm) fast

gen age=floor(treatagec)+distyrm

g byte treat=(inrange(treatagec,18,37.99))

egen distg=group(distyrm)
egen yrmg=group(yrm)
g byte postreform=(tyrm>=2008.25) & !mi(tyrm)

gen treatinyear=round((tyrm-floor(tyrm))*4)
gen misyear=treatinyear/4

/** Create postshock dummies **/
sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

** Load slightly different version of areg (only appropriate when clusters nest absorb variable) **
cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

keep if inrange(tyrm,2008.25,2012.25)

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

* Baseline
foreach var in inc earn {
		
reg `var' c.zbelow c.zabove 1.above c.misyear c.zbelow#c.misyear c.zabove#c.misyear 1.above#c.misyear i.distg#c.misyear i.distg#c.zabove#c.misyear i.distg#c.zbelow#c.misyear ib${base}.distg#1.above#c.misyear ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${base}.distg#1.above [pw=kwt]

global b_RD_`var'=0
global b_RD2_`var'=0

	forvalues y=5/13 {
	global b_RD_`var'=${b_RD_`var'} +(_b[_cons]+_b[`y'.distg])	
			if (`y'<8) {
			global b_RD2_`var'=${b_RD2_`var'} +(_b[_cons]+_b[`y'.distg])
			}
	}
}

* Estimates *
egen pnrnum=group(pnr)

foreach var in inc earn   {

qui ivreghdfe `var' i.distg#c.misyear i.distg#c.zabove#c.misyear i.distg#c.zbelow#c.misyear 1.postshock#1.above#c.misyear i.distg#c.zabove i.distg#c.zbelow  (firstpsyc=1.postshock#1.above)  [pw=kwt] if treatagec!=38 & distyrm<2, cluster(pnrnum)  absorb(pnrg yrmg distg)

global est_RD2_`var'=_b[firstpsyc]/12
global se_RD2_`var'=_se[firstpsyc]/12

qui ivreghdfe `var' i.distg#c.misyear i.distg#c.zabove#c.misyear i.distg#c.zbelow#c.misyear 1.postshock#1.above#c.misyear i.distg#c.zabove i.distg#c.zbelow  (firstpsyc=1.postshock#1.above)  [pw=kwt] if treatagec!=38 , cluster(pnrnum)  absorb(pnrg yrmg distg)

global est_RD_`var'=_b[firstpsyc]/12
global se_RD_`var'=_se[firstpsyc]/12

}

/** Create Table **/
mat X=J(6,6,.)
mat stars=J(6,6,0)

* Within 2 *
local j=1
foreach met in RDtime2 RD2  {
	
	local i=2
foreach var in inc earn  {
	
	cap mat X[`i',`j']=${est_`met'_`var'}
	cap mat X[`i',`j'+1]=${b_`met'_`var'}
	cap mat X[`i',`j'+2]=${se_`met'_`var'}

	cap mat stars[`i',`j']=(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.645)+(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.96) + (abs(${est_`met'_`var'}/${se_`met'_`var'})>2.58)
	
	local i=`i'+1
	}
local j=`j'+3
}

* Within 7 *
local j=1
foreach met in RDtime RD  {
	
	local i=5
foreach var in inc earn  {
	
	cap mat X[`i',`j']=${est_`met'_`var'}
	cap mat X[`i',`j'+1]=${b_`met'_`var'}
	cap mat X[`i',`j'+2]=${se_`met'_`var'}

	cap mat stars[`i',`j']=(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.645)+(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.96) + (abs(${est_`met'_`var'}/${se_`met'_`var'})>2.58)
	
	local i=`i'+1
	}
local j=`j'+3
}

frmttable using "I:\workdata\706727\Figs\LabormarketTable_BothMeth_YearlyLabor_FinalTable_Treatinmonth_Yearly.tex", tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c)  ///
ctitle("Method","RD in time", "RD" \ "Age range", "21-27", "37")   ///
sdec(0) rtitle("Within 2 years" \ ""  \ "" \ "Income" \ ""  \ ""   \  "Earnings" \ ""  \ "" \ "Within 7 years" \ ""  \ "" \ "Income" \ ""  \ ""   \  "Earnings" \ ""  \ "" )

frmttable using "I:\workdata\706727\Figs\LabormarketTable_BothMeth_YearlyLabor_FinalTable_Treatinmonth_Yearly.rtf",   replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c) ///
ctitle("Method","RD in time", "RD" \ "Age range", "21-27", "37")   ///
sdec(0) rtitle("Within 2 years" \ ""  \ "" \ "Income" \ ""  \ ""   \  "Earnings" \ ""  \ "" \ "Within 7 years" \ ""  \ "" \ "Income" \ ""  \ ""   \  "Earnings" \ ""  \ "" )


/*********************/
/********* 14 ********/
/*********************/


/**** RD-in-time ****/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,21,27.99)
keep if inrange(distyrm,-6,7)

keep pnr dupli distyrm treatagec tyrm yrm year agec firstpsyc inc earn 

** drop individuals just before cutoff ** 
drop if inrange(tyrm,2008,2008.25)

/* DEFLATE VARIABLES */
cap program drop deflat
do "I:\Workdata\706727\STATA Programs\deflat.do"
deflat earn 1 year 2020
deflat inc 1 year 2020

** Winsorize **
replace inc=0 if inc<0
replace earn=0 if earn<0
foreach var in  inc earn  {
sum `var' ,d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
replace `var'=r(p1) if `var'<r(p1) & !mi(`var') & r(p1)<0
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm)
gen tyrm2=floor(tyrm)
cap drop distyrm*
gen distyrm=yrm-tyrm2

keep if inrange(distyrm,-5,7)
gcollapse (mean) firstpsyc inc earn, by(pnr pnrg distyrm treatagec tyrm yrm) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen distg=group(distyrm)
egen yrmg=group(yrm)
egen tyrmg=group(tyrm)

sum tyrmg if tyrm==2008.25
global tyrm0=r(mean)
sum tyrmg
global tyrmmax=r(max)

gen treatinyear=round((tyrm-floor(tyrm))*4)
gen misyear=treatinyear/4

/** Create postshock dummies **/
sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

** Load slightly different version of areg (only appropriate when clusters nest absorb variable) **
cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

/*** Graphs ***/
cap postclose john
postfile john str30 var dist treat koef lower upper base using "I:\workdata\706727\Figs\PsykTestLongRunRD_YearlyLabor_RDtime", replace

local dmax=${max}
local dmin=${base}+${bdist}

foreach var in inc earn {

qui reg `var' 1.above c.zabove c.zbelow [pw=kwt] if tyrm!=2008.25 & distg==${base}
global cons=_b[_cons]+_b[1.above]

qui aregben `var'  i.yrmg  ib${maxm1}.bgdistg ib${maxm1}.bgdistg#c.misyear ib${maxm1}.bgdistg#(c.zabove c.zbelow) ib${maxm1}.bgdistg#(c.zabove c.zbelow)#c.misyear ib${maxm1}.bgdistg#1.above ib${maxm1}.bgdistg#1.above#c.misyear [pw=kwt] if tyrm!=2008.25 ,vce(cluster pnr) absorb(pnrg)

mat V=e(V)
mat b=e(b)

	forvalues d=1/`dmax' {

	global cont=_b[`d'.bgdistg]
	global secont=_se[`d'.bgdistg]
	global treat=_b[`d'.bgdistg#1.above]+_b[`d'.bgdistg]
	global setreat=sqrt(V["`d'.bgdistg#1.above","`d'.bgdistg#1.above"]+V["`d'.bgdistg","`d'.bgdistg"]+2*V["`d'.bgdistg#1.above","`d'.bgdistg"])
	
	post john ("`var'")  (`d') (0) (${cont}) (${cont}-1.96*${secont}) (${cont}+1.96*${secont})  (${cons})
	post john ("`var'")  (`d') (1) (${treat}) (${treat}-1.96*${setreat}) (${treat}+1.96*${setreat})  (${cons})
	}
	
}
postclose john


/***** RD *******/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(tyrm,2008.25,2012.25)
keep if inrange(treatagec,28,50)
keep if inrange(distyrm,-6,7)

keep pnr dupli distyrm treatagec tyrm yrm year agec firstpsyc inc earn   

/* DEFLATE VARIABLES */
cap program drop deflat
do "I:\Workdata\706727\STATA Programs\deflat.do"
deflat earn 1 year 2020
deflat inc 1 year 2020

** Winsorize **
replace inc=0 if inc<0
replace earn=0 if earn<0
foreach var in  inc earn  {
sum `var' ,d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
replace `var'=r(p1) if `var'<r(p1) & !mi(`var') & r(p1)<0
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm)
gen tyrm2=floor(tyrm)
cap drop distyrm*
gen distyrm=yrm-tyrm2

keep if inrange(distyrm,-5,7)
gcollapse (mean) firstpsyc inc earn , by(pnr pnrg distyrm treatagec tyrm yrm) fast

gen age=floor(treatagec)+distyrm

g byte treat=(inrange(treatagec,18,37.99))

egen distg=group(distyrm)
egen yrmg=group(yrm)
g byte postreform=(tyrm>=2008.25) & !mi(tyrm)

gen treatinyear=round((tyrm-floor(tyrm))*4)
gen misyear=treatinyear/4

/** Create postshock dummies **/
sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg2
gen bgdistg2=distg
replace bgdistg2=${max} if distg==${base}
replace bgdistg2=${base} if distg==${max}

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

** Load slightly different version of areg (only appropriate when clusters nest absorb variable) **
cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"


/** Figure **/

cap postclose john
postfile john str30 var dist treat koef lower upper base using "I:\workdata\706727\Figs\PsykTestLongRunRD_YearlyLabor_RD", replace

qui sum yrmg 
local ymax=r(max)

local dmax=${max}
local dmin=${base}+${bdist}

foreach var in inc earn   {

qui reg `var' 1.above c.zabove c.zbelow [pw=kwt] if treatage!=38 & distg==${base}
global cons=_b[_cons]+_b[1.above]

qui aregben `var'  ibn.yrmg  ib${maxm1}.bgdistg ib${maxm1}.bgdistg#c.misyear ib${maxm1}.bgdistg#(c.zabove c.zbelow) ib${maxm1}.bgdistg#(c.zabove c.zbelow)#c.misyear ib${maxm1}.bgdistg#1.above ib${maxm1}.bgdistg#1.above#c.misyear [pw=kwt] if treatage!=38 ,vce(cluster pnr) absorb(pnrg)
 
mat V=e(V)
mat b=e(b)

	forvalues d=1/`dmax' {

	global cont=_b[`d'.bgdistg]
	global secont=_se[`d'.bgdistg]
	global treat=_b[`d'.bgdistg#1.above]+_b[`d'.bgdistg]
	global setreat=sqrt(V["`d'.bgdistg#1.above","`d'.bgdistg#1.above"]+V["`d'.bgdistg","`d'.bgdistg"]+2*V["`d'.bgdistg#1.above","`d'.bgdistg"])
	
	post john ("`var'") (`d') (0) (${cont}) (${cont}-1.96*${secont}) (${cont}+1.96*${secont})  (${cons})
	post john ("`var'") (`d') (1) (${treat}) (${treat}-1.96*${setreat}) (${treat}+1.96*${setreat})  (${cons})
	}
}
postclose john


/* Create figures */
global max=13
global base=5
global maxm1=12
global bdist=1

preserve
clear all
cd "I:\Workdata\706727\Figs"
use PsykTestLongRunRD_YearlyLabor_RDtime

gen meth="RDtime"
gen ageg=1

append using PsykTestLongRunRD_YearlyLabor_RD
replace meth="RD" if mi(meth)
replace ageg=2 if mi(ageg)

gen olddist=dist
replace dist=${base} if olddist==${max} 
replace dist=${max} if olddist==${base}  
replace dist=1 if olddist==${maxm1}  
replace dist=${maxm1} if olddist==1  

sort var dist 

replace dist=(dist-${base}-${bdist})

** Baselines **
foreach var in inc earn    {
	foreach m in RDtime RD {
	sum base if var=="`var'" & meth=="`m'"
	global  dibase`var'_`m': di %10.0f r(mean)
	}
}

/** Graph for main paper ***/
foreach var in inc earn    {

if ("`var'"=="inc") {
local tit2 "Income"
local xops `"xlabel(-5(1)7,labsize(medlarge)) xscale(titlegap(*4)) xtitle("")"'
local ylab "-100000(50000)50000"
}
if ("`var'"=="earn") {
local tit2 "Earnings"
local xops `"xlabel(-5(1)7,labsize(medlarge)) xscale(titlegap(*4)) xtitle("")"'
local ylab "-100000(50000)50000"
}
local ttit1 "ES-RD-Time: Age 21-27"	
local ttit3 "ES-RD: Age 37"


twoway 	(rcap lower upper dist if var=="`var'"  & treat==0 & meth=="RDtime", color(black))  ///
		(rcap lower upper dist if var=="`var'"  & treat==1 & meth=="RDtime", color(red))  ///
		(connect koef dist if var=="`var'"  & treat==0 & meth=="RDtime", color(black) mfcolor(white))  ///
		(connect koef dist if var=="`var'"  & treat==1 & meth=="RDtime", color(red) ) ///
		,graphregion(color(white)) `xops' ytitle("DKK",size(medlarge)) ///
title("`ttit1'", color(black) size(medium)) legend(order(4 "Treatment" 3 "Control") rows(2) pos(7) ring(0) region(color(white) margin(small)) size(medium)) ///
 text(35000 3.5 "Baseline:""${dibase`var'_RDtime}" , box lcolor(white) fcolor(white)) ///
 xscale(titlegap(*4)) ylabel(`ylab',labsize(none)) yscale(titlegap(*4)) xsize(6) ysize(4) xline(0, lcolor(black)) name(RDtime, replace)

if ("`var'"!="earn") {
twoway 	(rcap lower upper dist if var=="`var'"  & treat==0 & meth=="RD", color(black))  ///
		(rcap lower upper dist if var=="`var'"  & treat==1 & meth=="RD", color(red))  ///
		(connect koef dist if var=="`var'"  & treat==0 & meth=="RD", color(black) mfcolor(white))  ///
		(connect koef dist if var=="`var'"  & treat==1 & meth=="RD", color(red) ) ///
		,graphregion(color(white)) `xops' ytitle("") text(35000 3.5 "Baseline:""${dibase`var'_RD}" , box lcolor(white)  fcolor(white)) ///
legend(order(4 "Treatment" 3 "Control") rows(2) pos(7) ring(0) region(color(white) margin(small)) size(medsmall)) title("`ttit3'", color(black) size(medium)) ///
ylabel(`ylab',labsize(none)) xscale(titlegap(*4)) yscale(off)  xsize(5) ysize(4) xline(0, lcolor(black)) name(RD, replace)

graph combine RDtime RD,  rows(1) graphregion(color(white) margin(small)) title("`tit2'", color(black) size(medsmall))  name(`var', replace) ycommon 

}
if ("`var'"=="earn") {
twoway 	(rcap lower upper dist if var=="`var'"  & treat==0 & meth=="RD", color(black))  ///
		(rcap lower upper dist if var=="`var'"  & treat==1 & meth=="RD", color(red))  ///
		(connect koef dist if var=="`var'"  & treat==0 & meth=="RD", color(black) mfcolor(white))  ///
		(connect koef dist if var=="`var'"  & treat==1 & meth=="RD", color(red) ) ///
		,graphregion(color(white)) `xops' ytitle("") text(35000 3.5 "Baseline:""${dibase`var'_RD}" , box lcolor(white)  fcolor(white)) ///
legend(order(4 "Treatment" 3 "Control") rows(2) pos(7) ring(0) region(color(white) margin(small)) size(medsmall)) title("`ttit3'", color(black) size(medium)) ///
ylabel(`ylab',labsize(none)) xscale(titlegap(*4)) yscale(off)  xsize(5) ysize(4) xline(0, lcolor(black)) name(RD, replace)
	
graph combine RDtime RD,  rows(1) graphregion(color(white) margin(vtiny)) title("`tit2'", color(black) size(medsmall)) name(`var', replace) ycommon 
}

}
graph combine inc earn , iscale(*0.85) graphregion(color(white) margin(small))  ycommon rows(2) name(john,replace)

graph display john ,xsize(17) ysize(20)

graph export "I:\Workdata\706727\Figs\PsykTestLongRunRD_YearlyLabor.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\PsykTestLongRunRD_YearlyLabor.eps", replace 

restore


/*********************/
/********* 15 ********/
/*********************/

/**** Data Preb estimates ****/
clear 
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,18,50)
keep if inrange(distyrm,-5,7)

keep pnr dupli distyrm treatagec tyrm yrm agec docvisit specdoc medphyc inpat outpat er psyc Dpsyc firstpsyc 

foreach var in psyc docvisit specdoc medphyc inpat outpat er {
replace `var'=0 if `var'<0 | mi(`var')
}

/* Winzorize */
foreach var in psyc docvisit specdoc medphyc inpat outpat er {
qui sum `var' if `var'>0 & !mi(`var'), d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

keep if distyrm<2
gcollapse (mean) psyc firstpsyc docvisit specdoc medphyc inpat outpat er, by(pnr pnrg distyrm treatagec tyrm yrm) fast

g byte treat=(inrange(treatagec,18,37.99))

egen distg=group(distyrm)
egen yrmg=group(yrm)
g byte postreform=(tyrm>=2008.25) & !mi(tyrm)
destring(pnr), gen(numpnr)

/** Create postshock dummies **/

sum distg 
global max=r(max)
global maxm1=r(max)-1

sum distg if distyrm==0
global base=r(max)-1

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

* Find cumulative treatment on individual-level *
gen psyc1=(firstpsyc>0 & !mi(firstpsyc)) if !mi(firstpsyc)
cap drop maxfirstpsyc maxmaxfirstpsyc
bysort pnrg: egen maxfirstpsyc=max(psyc1) if distg>20 & distg<28
by pnrg: egen maxmaxfirstpsyc=max(maxfirstpsyc)

compress

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

/**** RD in time ****/

* Standard errors *
preserve
clear 
use "I:\Workdata\706727\Figs\PsykTestLongRun_PooledTable_FullPerDist_RDtime_Bootstrap"
keep if dist<=27

bysort it var: egen sumkoef=sum(koef)

keep it var sumkoef
duplicates drop

gen temp=sumkoef if var=="firstpsyc"
bysort it: egen firststage=max(temp)
	
gen secondstage=sumkoef/firststage

sum sumkoef if  var=="firstpsyc"
global sefirstpsyc=r(sd)

* Second stage *
foreach var in  psyc docvisit specdoc medphyc inpat outpat er   {

sum secondstage if var=="`var'"
global se`var'=r(sd)
}
restore


g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen tyrmg=group(tyrm)

mat X=J(8,6,.)
mat stars=J(8,6,0)

preserve
keep if inrange(treatagec,18,27.99)
keep if !inrange(tyrm,2008,2008.25)

* First stage *
local j=1
local i=1

* Baseline 
reg firstpsyc c.zbelow c.zabove 1.above ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${base}.distg#1.above [pw=kwt]

global baseprob_RDtime=0
forvalues y=20/27 {
global baseprob_RDtime=${baseprob_RDtime} +(_b[_cons]+_b[`y'.distg])*3	
}

* Estimate 
aregben firstpsyc i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt], absorb(pnrg) vce(cluster pnr)
mat V=e(V)
mat b=e(b)
mat se=J(1,27-20+1,1)*V["20.distgpoolpre#1.above".."27.distgpoolpre#1.above","20.distgpoolpre#1.above".."27.distgpoolpre#1.above"]*J(27-20+1,1,1)
global se=sqrt(se[1,1])

global firststage=0
forvalues y=20/27 {
global firststage=${firststage}+_b[`y'.distgpoolpre#1.above]
}

mat X[`i',`j']=${firststage}*3*100
mat X[`i',`j'+1]=${baseprob_RDtime}*100
mat X[`i',`j'+2]=${se}*3*100
mat stars[`i',`j']=(abs(${firststage}/${se})>1.645)+(abs(${firststage}/${se})>1.96) + (abs(${firststage}/${se})>2.58)

* Baseline 
foreach var in  docvisit specdoc medphyc inpat outpat er  {
		
reg `var' c.zbelow c.zabove 1.above ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${base}.distg#1.above [pw=kwt]

global baseprob_RDtime_`var'=0
forvalues y=20/27 {
global baseprob_RDtime_`var'=${baseprob_RDtime_`var'} +(_b[_cons]+_b[`y'.distg])*3	
}
}

* Psychologist services *
local j=1
local i=2

aregben psyc i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt], absorb(pnrg)

global secondstage=0
forvalues y=20/27 {
global secondstage=${secondstage}+_b[`y'.distgpoolpre#1.above]
}

mat X[`i',`j']=${secondstage}/${firststage}
mat X[`i',`j'+2]=${sepsyc}
mat stars[`i',`j']=(abs((${secondstage}/${firststage})/${sepsyc})>1.645)+(abs((${secondstage}/${firststage})/${sepsyc})>1.96) + (abs((${secondstage}/${firststage})/${sepsyc})>2.58)

* Second stage *
local i=3
foreach var in docvisit specdoc medphyc inpat outpat er {

aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt], absorb(pnrg) 

global secondstage=0
forvalues y=20/27 {
global secondstage=${secondstage}+_b[`y'.distgpoolpre#1.above]
}

mat X[`i',`j']=${secondstage}/${firststage}
mat X[`i',`j'+2]=${se`var'}
mat stars[`i',`j']=(abs((${secondstage}/${firststage})/${se`var'})>1.645)+(abs((${secondstage}/${firststage})/${se`var'})>1.96) + (abs((${secondstage}/${firststage})/${se`var'})>2.58)

mat X[`i',`j'+1]=${baseprob_RDtime_`var'}

local i=`i'+1
}

restore

/** RD 37 **/
keep if inrange(tyrm,2008.25,2012.25)
keep if inrange(treatagec,30,47)

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

* First stage *
local j=4
local i=1

* Baseline 
reg firstpsyc c.zbelow c.zabove 1.above ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${base}.distg#1.above [pw=kwt]

global baseprob_RD=0
forvalues y=20/27 {
global baseprob_RD=${baseprob_RD} +(_b[_cons]+_b[`y'.distg])*3	
}

* Estimate
qui aregben firstpsyc i.yrmg ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove 1.postshock#1.above  [pw=kwt]  if treatagec!=38, absorb(pnrg) vce(cluster pnr) 

mat X[`i',`j']=_b[1.postshock#1.above]*3*(27-20+1)*100
mat X[`i',`j'+1]=${baseprob_RD}*100
mat X[`i',`j'+2]=_se[1.postshock#1.above]*3*(27-20+1)*100
mat stars[`i',`j']=(abs(_b[1.postshock#1.above]/_se[1.postshock#1.above])>1.645)+(abs(_b[1.postshock#1.above]/_se[1.postshock#1.above])>1.96) + (abs(_b[1.postshock#1.above]/_se[1.postshock#1.above])>2.58)

* Number of psychologist services *
local j=4
local i=2
qui ivreghdfe psyc  ib${base}o1.distg#c.zabove ib${base}o1.distg#c.zbelow (firstpsyc=1.postshock#1.above)  [pw=kwt] if treatage!=38 ,cluster(numpnr)  absorb(pnrg yrmg distg)
eststo reg1

mat X[`i',`j']=_b[firstpsyc]
mat X[`i',`j'+2]=_se[firstpsyc]
mat stars[`i',`j']=(abs(_b[firstpsyc]/_se[firstpsyc])>1.645)+(abs(_b[firstpsyc]/_se[firstpsyc])>1.96) + (abs(_b[firstpsyc]/_se[firstpsyc])>2.58)

* Baseline 
foreach var in  docvisit specdoc medphyc inpat outpat er  {
		
reg `var' c.zbelow c.zabove 1.above ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${base}.distg#1.above [pw=kwt]

global baseprob_RD_`var'=0
forvalues y=20/27 {
global baseprob_RD_`var'=${baseprob_RD_`var'} +(_b[_cons]+_b[`y'.distg])*3	
}
}

* Second stage *
local i=3
foreach var in docvisit specdoc medphyc inpat outpat er {

qui ivreghdfe `var'  ib${base}o1.distg#c.zabove ib${base}o1.distg#c.zbelow (firstpsyc=1.postshock#1.above)  [pw=kwt] if treatagec!=38 ,cluster(numpnr)  absorb(pnrg yrmg distg)

mat X[`i',`j']=_b[firstpsyc]
mat X[`i',`j'+2]=_se[firstpsyc]
mat stars[`i',`j']=(abs(_b[firstpsyc]/_se[firstpsyc])>1.645)+(abs(_b[firstpsyc]/_se[firstpsyc])>1.96) + (abs(_b[firstpsyc]/_se[firstpsyc])>2.58)

mat X[`i',`j'+1]=${baseprob_RD_`var'}

local i=`i'+1
}

frmttable using "I:\workdata\706727\Figs\LabormarketTable_BothMeth_Final_LimPer.tex", tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c)  ///
ctitle("Method","RD in time", "RD" \ "Age range", "18-27", "37")   ///
sdec(2) rtitle("Psychologist (share)" \ "" \ "" \"Psychologist (services)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" )

frmttable using "I:\workdata\706727\Figs\LabormarketTable_BothMeth_Final_LimPer.rtf",   replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c) ///
ctitle("Method","RD in time", "RD" \ "Age range", "18-27", "37")   ///
sdec(2) rtitle("Psychologist (share)" \ "" \ "" \"Psychologist (services)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" )


/*********************/
/********* 16 ********/
/*********************/

/* RDDID - 18 Individuals */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

destring(kom),replace
merge m:1 kom year using  "I:\Workdata\706727\Build\Data\ChildhospByKomYear.dta" 
keep if _merge==3
drop _merge

* Same sample as year_collapse *
drop if year==2012 & month>3
keep if inrange(agec,15,23) 

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1
replace firstpsykhosp=firstpsykhospAnxDep

cap drop man
gen man=(koen==1)

/* Estimates are not directly comparable to DID results */
foreach var in firstpsyc firstpsykhosp firstadep firstsui {
replace `var'=`var'*100*12
}

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gen cutoff2006=cutoff if year==2006
bysort kom: egen max=max(cutoff2006)
replace cutoff2006=max
drop max

/* Regression */
gen belowcutoff=(agec<cutoff)

g byte above=(agec>=18) if !mi(agec)
g byte below=(agec<18) if !mi(agec)

g double dist=agec-18
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,2.5-abs(dist))

/* By gender */
forvalues m=0/1 {

	foreach var in firstpsyc firstpsykhosp firstadep firstsui {

	qui reg `var' 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff  1.Dyear#(1.above c.zabove c.zbelow)  [pw=kwt] if agec!=18  & man==`m' , vce(cluster pnr)
	
	global est_18_`m'_`var'=_b[1.Dyear#1.above]
	global se_18_`m'_`var'=_se[1.Dyear#1.above]
	
	global b_18_`m'_`var'=_b[_cons]+_b[1.above]+_b[1.Dyear]

* Base level *
qui levelsof cutoff, local(lev)

	qui count if e(sample)==1
	local tot=r(N)
	
	foreach l of local lev {
	
	qui count if e(sample)==1 & cutoff==`l' & man==`m'
	local share=r(N)

		if (`l'<18) {
		global b_18_`m'_`var'=${b_18_`m'_`var'}+(`share'/`tot')*_b[`l'.cutoff]
		}
		if (`l'>18) {
		global b_18_`m'_`var'=${b_18_`m'_`var'}+(`share'/`tot')*(_b[`l'.cutoff]+_b[`l'.cutoff#1.belowcutoff])
		}
		}
	}
}

* Difference between genders *
foreach var in firstpsyc firstpsykhosp firstadep firstsui {

qui reg `var' 0.man 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff  1.Dyear#(1.above c.zabove c.zbelow) (1.above c.zabove c.zbelow 1.Dyear  1.Dyear#(1.above c.zabove c.zbelow))#0.man  [pw=kwt] if agec!=18  , vce(cluster pnr)


global est_18_2_`var'=_b[1.Dyear#1.above#0.man]
global b_18_2_`var'=${b_18_0_`var'}-${b_18_1_`var'}
global se_18_2_`var'=_se[1.Dyear#1.above#0.man]
}


/* Regression Discontinuity 37 */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)
* Same sample as year_collapse *
drop if year==2012 & month>3
keep if inrange(agec,28,46) 

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

keep if Dyear==1

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)
replace firstpsykhosp=firstpsykhosp*AnxDep

foreach var in firstpsyc firstpsykhosp firstadep firstsui {
replace `var'=`var'*100*12
}

cap drop man
gen man=(koen==1)

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

/* By gender */
forvalues m=0/1 {

	foreach var in firstpsyc firstpsykhosp firstadep firstsui {

	qui reg `var' 1.above c.zabove c.zbelow   [pw=kwt] if agec!=38  & man==`m', vce(cluster pnr)

	global est_37_`m'_`var'=_b[1.above]
	global b_37_`m'_`var'=_b[_cons]
	global se_37_`m'_`var'=_se[1.above]
	}
}

* Difference between genders *
foreach var in firstpsyc firstpsykhosp firstadep firstsui {

qui reg `var' 0.man 1.above c.zabove c.zbelow (1.above c.zabove c.zbelow)#0.man  [pw=kwt] if agec!=38 , vce(cluster pnr)

global est_37_2_`var'=_b[1.above#0.man]
global b_37_2_`var'=${b_37_0_`var'}-${b_37_1_`var'}
global se_37_2_`var'=_se[1.above#0.man]
}

/*****  Create Tables  *****/
clear

mat X=J(4,18,.)
mat stars=J(4,18,0)

local j=1
foreach met in 18_0 18_1 18_2 37_0 37_1 37_2  {
	
	local i=1
	foreach var in firstpsyc firstpsykhosp firstadep firstsui {
	
	mat X[`i',`j']=${est_`met'_`var'}
	mat X[`i',`j'+1]=${b_`met'_`var'}
	mat X[`i',`j'+2]=${se_`met'_`var'}
	
	mat stars[`i',`j']=(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.645)+(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.96) + (abs(${est_`met'_`var'}/${se_`met'_`var'})>2.58)
	
	local i=`i'+1
	}
local j=`j'+3
}

frmttable using I:\workdata\706727\Figs\Final_FiguresAndTables_MHGenderHet.tex, tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,)) basefont(fs12) statfont(fs11)  coljust(l c) ///
ctitle("Method", "RD-DID", " ", " ", "RD", " ", " " \ "Age group", "18", " ", " ", "37", " ", " " \ "", "Women", "Men", "Difference","Women", "Men", "Difference")   ///
sdec(3) ///
rtitle("Psychologist" \" " \ " " \ "Psychiatric hospital" \" " \ " " \  "Antidepressants" \" " \ " " \ "Suicide Attempts" \ " " \ " ") ///
multicol(1,2,3;1,5,3;1,8,3;2,2,3;2,5,3;2,8,3)

frmttable using I:\workdata\706727\Figs\Final_FiguresAndTables_MHGenderHet.rtf, replace statmat(X) sub(2) annotate(stars)  asymbol(*,**,***) brackets("","" \ [,] \ (,)) coljust(l c)  basefont(fs12) statfont(fs11)  ///
ctitle("Method", "RD-DID", " ", " ", "RD", " ", " " \ "Age group", "18", " ", " ", "37", " ", " " \ "", "Women", "Men", "Difference","Women", "Men", "Difference")   ///
sdec(3) ///
rtitle("Psychologist" \" " \ " " \ "Psychiatric hospital" \" " \ " " \  "Antidepressants" \" " \ " " \ "Suicide Attempts" \ " " \ " ") ///
multicol(1,2,3;1,5,3;1,8,3;2,2,3;2,5,3;2,8,3)


/*********************/
/********* 17 ********/
/*********************/

/* RD-DID - 18 Individuals */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

destring(kom),replace
merge m:1 kom year using  "I:\Workdata\706727\Build\Data\ChildhospByKomYear.dta" 
keep if _merge==3
drop _merge

* Same sample as year_collapse *
drop if year==2012 & month>3
keep if inrange(agec,15,23) 

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1
replace firstpsykhosp=firstpsykhospAnxDep

/* Estimates are not directly comparable to DID results */
foreach var in firstpsyc firstpsykhosp firstadep firstsui {
replace `var'=`var'*100*12
}

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gen cutoff2006=cutoff if year==2006
bysort kom: egen max=max(cutoff2006)
replace cutoff2006=max
drop max

/* Merge with parental income five years prior */
rename year year2
gen year=year2-5
merge m:1 pnr year using incdata, keepusing(pnr year incf incm)

keep if _merge==3
drop year _merge 
rename year2 year

egen income=rowmean(incf incm) 
drop incf incm

/* Create income ranks */
drop if mi(income)

set seed 112
gen double random=runiform()
replace random=(random-0.5)/_N

sort year age koen income random
by year age koen: gen double incrank=_n
by year age koen: gen double maxincrank=_N
replace incrank=ceil((((incrank-0.5)/maxincrank)*100+random)/(100/3))

/* Regression */
gen belowcutoff=(agec<cutoff)

g byte above=(agec>=18) if !mi(agec)
g byte below=(agec<18) if !mi(agec)

g double dist=agec-18
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,2.5-abs(dist))

/* By Inc */
forvalues m=1/3 {

	foreach var in firstpsyc firstpsykhosp firstadep firstsui {

	qui reg `var' 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff  1.Dyear#(1.above c.zabove c.zbelow)  [pw=kwt] if agec!=18  & incrank==`m' , vce(cluster pnr)
	
	global est_18_`m'_`var'=_b[1.Dyear#1.above]
	global se_18_`m'_`var'=_se[1.Dyear#1.above]
	
	global b_18_`m'_`var'=_b[_cons]+_b[1.above]+_b[1.Dyear]

* Base level *
qui levelsof cutoff, local(lev)

	qui count if e(sample)==1
	local tot=r(N)
	
	foreach l of local lev {
	
	qui count if e(sample)==1 & cutoff==`l' & incrank==`m'
	local share=r(N)

		if (`l'<18) {
		global b_18_`m'_`var'=${b_18_`m'_`var'}+(`share'/`tot')*_b[`l'.cutoff]
		}
		if (`l'>18) {
		global b_18_`m'_`var'=${b_18_`m'_`var'}+(`share'/`tot')*(_b[`l'.cutoff]+_b[`l'.cutoff#1.belowcutoff])
		}
		}
	}
}

/* Regression Discontinuity 37 */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)
* Same sample as year_collapse *
drop if year==2012 & month>3
keep if inrange(agec,28,46) 

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

keep if Dyear==1

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)
replace firstpsykhosp=firstpsykhosp*AnxDep

foreach var in firstpsyc firstpsykhosp firstadep firstsui {
replace `var'=`var'*100*12
}

/* Merge with income */
rename year year2
gen year=year-2
merge m:1 pnr year using incdata, keepusing(pnr year inc)

keep if _merge==3
drop year _merge
rename year2 year

/* Create income ranks */
set seed 112
gen double random=runiform()
replace random=(random-0.5)/_N

drop if mi(inc)

sort year age koen inc random
by year age koen: gen double incrank=_n
by year age koen: gen double maxincrank=_N
replace incrank=ceil((((incrank-0.5)/maxincrank)*100+random)/(100/3))

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

/* By gender */
forvalues m=1/3 {

	foreach var in firstpsyc firstpsykhosp firstadep firstsui {

	qui reg `var' 1.above c.zabove c.zbelow   [pw=kwt] if agec!=38  & incrank==`m', vce(cluster pnr)

	global est_37_`m'_`var'=_b[1.above]
	global b_37_`m'_`var'=_b[_cons]
	global se_37_`m'_`var'=_se[1.above]
	}
}

/*****  Create Tables  *****/
clear

mat X=J(4,18,.)
mat stars=J(4,18,0)

local j=1
foreach met in 18_1 18_2 18_3 37_1 37_2 37_3  {
	
	local i=1
	foreach var in firstpsyc firstpsykhosp firstadep firstsui {
	
	mat X[`i',`j']=${est_`met'_`var'}
	mat X[`i',`j'+1]=${b_`met'_`var'}
	mat X[`i',`j'+2]=${se_`met'_`var'}
	
	mat stars[`i',`j']=(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.645)+(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.96) + (abs(${est_`met'_`var'}/${se_`met'_`var'})>2.58)
	
	local i=`i'+1
	}
local j=`j'+3
}

frmttable using I:\workdata\706727\Figs\Final_FiguresAndTables_MHIncHet.tex, tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,)) basefont(fs12) statfont(fs11)  coljust(l c) ///
ctitle("Method", "RD-DID", " ", " ", "RD", " ", " " \ "Age group", "18", " ", " ", "37", " ", " " \ "", "Women", "Men", "Difference","Women", "Men", "Difference")   ///
sdec(3) ///
rtitle("Psychologist" \" " \ " " \ "Psychiatric hospital" \" " \ " " \  "Antidepressants" \" " \ " " \ "Suicide Attempts" \ " " \ " ") ///
multicol(1,2,3;1,5,3;1,8,3;2,2,3;2,5,3;2,8,3)

frmttable using I:\workdata\706727\Figs\Final_FiguresAndTables_MHIncHet.rtf, replace statmat(X) sub(2) annotate(stars)  asymbol(*,**,***) brackets("","" \ [,] \ (,)) coljust(l c)  basefont(fs12) statfont(fs11)  ///
ctitle("Method", "RD-DID", " ", " ", "RD", " ", " " \ "Age group", "18", " ", " ", "37", " ", " " \ "", "Women", "Men", "Difference","Women", "Men", "Difference")   ///
sdec(3) ///
rtitle("Psychologist" \" " \ " " \ "Psychiatric hospital" \" " \ " " \  "Antidepressants" \" " \ " " \ "Suicide Attempts" \ " " \ " ") ///
multicol(1,2,3;1,5,3;1,8,3;2,2,3;2,5,3;2,8,3)


/*********************/
/********* 18 ********/
/*********************/

/* RDDID - 18 Individuals */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

destring(kom),replace
merge m:1 kom year using  "I:\Workdata\706727\Build\Data\ChildhospByKomYear.dta" 
keep if _merge==3
drop _merge

* Same sample as year_collapse *
drop if year==2012 & month>3
keep if inrange(agec,15,23) 

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1
replace firstpsykhosp=firstpsykhospAnxDep

gen byte famany_fam=((famany_child>0 & !mi(famany_child)) | (famany_par>0 & !mi(famany_par)) | (famany_sib>0 & !mi(famany_sib)))

/** Use values from one year prior **/
sort pnr year
by pnr: gen lagfamany_fam=famany_fam[_n-1] if pnr==pnr[_n-1] 
replace famany_fam=lagfamany_fam

/* Estimates are not directly comparable to DID results */
foreach var in firstpsyc firstpsykhosp firstadep firstsui {
replace `var'=`var'*100*12
}

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gen cutoff2006=cutoff if year==2006
bysort kom: egen max=max(cutoff2006)
replace cutoff2006=max
drop max

/* Regression */
gen belowcutoff=(agec<cutoff)

g byte above=(agec>=18) if !mi(agec)
g byte below=(agec<18) if !mi(agec)

g double dist=agec-18
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,2.5-abs(dist))

/* By MH history */
forvalues m=0/1 {

	foreach var in firstpsyc firstpsykhosp firstadep firstsui {

	qui reg `var' 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff  1.Dyear#(1.above c.zabove c.zbelow)  [pw=kwt] if agec!=18  & famany_fam==`m' , vce(cluster pnr)
	
	global est_18_`m'_`var'=_b[1.Dyear#1.above]
	global se_18_`m'_`var'=_se[1.Dyear#1.above]
	
	global b_18_`m'_`var'=_b[_cons]+_b[1.above]+_b[1.Dyear]

* Base level *
qui levelsof cutoff, local(lev)

	qui count if e(sample)==1
	local tot=r(N)
	
	foreach l of local lev {
	
	qui count if e(sample)==1 & cutoff==`l' & famany_fam==`m'
	local share=r(N)

		if (`l'<18) {
		global b_18_`m'_`var'=${b_18_`m'_`var'}+(`share'/`tot')*_b[`l'.cutoff]
		}
		if (`l'>18) {
		global b_18_`m'_`var'=${b_18_`m'_`var'}+(`share'/`tot')*(_b[`l'.cutoff]+_b[`l'.cutoff#1.belowcutoff])
		}
		}
	}
}

* Difference between MH history *
foreach var in firstpsyc firstpsykhosp firstadep firstsui {

qui reg `var' 0.famany_fam 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff  1.Dyear#(1.above c.zabove c.zbelow) (1.above c.zabove c.zbelow 1.Dyear  1.Dyear#(1.above c.zabove c.zbelow))#0.famany_fam  [pw=kwt] if agec!=18  , vce(cluster pnr)


global est_18_2_`var'=_b[1.Dyear#1.above#0.famany_fam]
global b_18_2_`var'=${b_18_0_`var'}-${b_18_1_`var'}
global se_18_2_`var'=_se[1.Dyear#1.above#0.famany_fam]
}

/* Regression Discontinuity 37 */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)
* Same sample as year_collapse *
drop if year==2012 & month>3
keep if inrange(agec,28,46) 

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

keep if Dyear==1

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)
replace firstpsykhosp=firstpsykhosp*AnxDep

foreach var in firstpsyc firstpsykhosp firstadep firstsui {
replace `var'=`var'*100*12
}

gen byte famany_fam=((famany_child>0 & !mi(famany_child)) | (famany_par>0 & !mi(famany_par)) | (famany_sib>0 & !mi(famany_sib)))

/** Use values from one year prior **/
sort pnr year
by pnr: gen lagfamany_fam=famany_fam[_n-1] if pnr==pnr[_n-1] 
replace famany_fam=lagfamany_fam

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

/* By gender */
forvalues m=0/1 {

	foreach var in firstpsyc firstpsykhosp firstadep firstsui {

	qui reg `var' 1.above c.zabove c.zbelow   [pw=kwt] if agec!=38  & famany_fam==`m', vce(cluster pnr)

	global est_37_`m'_`var'=_b[1.above]
	global b_37_`m'_`var'=_b[_cons]
	global se_37_`m'_`var'=_se[1.above]
	}
}
* Difference between genders *
foreach var in firstpsyc firstpsykhosp firstadep firstsui {

qui reg `var' 0.famany_fam 1.above c.zabove c.zbelow (1.above c.zabove c.zbelow)#0.famany_fam  [pw=kwt] if agec!=38 , vce(cluster pnr)

global est_37_2_`var'=_b[1.above#0.famany_fam]
global b_37_2_`var'=${b_37_0_`var'}-${b_37_1_`var'}
global se_37_2_`var'=_se[1.above#0.famany_fam]
}

/*****  Create Tables  *****/
clear

mat X=J(4,27,.)
mat stars=J(4,27,0)

local j=1
foreach met in 18_0 18_1 18_2  37_0 37_1 37_2  {
	
	local i=1
	foreach var in firstpsyc firstpsykhosp firstadep firstsui {
	
	mat X[`i',`j']=${est_`met'_`var'}
	mat X[`i',`j'+1]=${b_`met'_`var'}
	mat X[`i',`j'+2]=${se_`met'_`var'}
	
	mat stars[`i',`j']=(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.645)+(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.96) + (abs(${est_`met'_`var'}/${se_`met'_`var'})>2.58)
	
	local i=`i'+1
	}
local j=`j'+3
}


frmttable using I:\workdata\706727\Figs\Final_FiguresAndTables_MHFAMHet.tex, tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,)) basefont(fs12) statfont(fs11)  coljust(l c) ///
ctitle("Method", "RD-DID", " ", " ", "RD", " ", " " \ "Age group", "18", " ", " ", "37", " ", " " \ "", "Women", "Men", "Difference","Women", "Men", "Difference")   ///
sdec(3) ///
rtitle("Psychologist" \" " \ " " \ "Psychiatric hospital" \" " \ " " \  "Antidepressants" \" " \ " " \ "Suicide Attempts" \ " " \ " ") ///
multicol(1,2,3;1,5,3;1,8,3;2,2,3;2,5,3;2,8,3)

frmttable using I:\workdata\706727\Figs\Final_FiguresAndTables_MHFAMHet.rtf, replace statmat(X) sub(2) annotate(stars)  asymbol(*,**,***) brackets("","" \ [,] \ (,)) coljust(l c)  basefont(fs12) statfont(fs11)  ///
ctitle("Method", "RD-DID", " ", " ", "RD", " ", " " \ "Age group", "18", " ", " ", "37", " ", " " \ "", "Women", "Men", "Difference","Women", "Men", "Difference")   ///
sdec(3) ///
rtitle("Psychologist" \" " \ " " \ "Psychiatric hospital" \" " \ " " \  "Antidepressants" \" " \ " " \ "Suicide Attempts" \ " " \ " ") ///
multicol(1,2,3;1,5,3;1,8,3;2,2,3;2,5,3;2,8,3)


/*********************/
/********* 19 ********/
/*********************/

/**** Data Preb estimates ****/
clear 
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,18,50)
keep if inrange(distyrm,-5,7)

keep pnr koen dupli distyrm treatagec tyrm yrm agec docvisit specdoc medphyc inpat outpat er psyc Dpsyc firstpsyc 

gen koen0=koen if distyrm==0
bysort pnr dupli: egen maxkoen=max(koen0)
replace koen=maxkoen
drop maxkoen koen0

foreach var in psyc docvisit specdoc medphyc inpat outpat er {
replace `var'=0 if `var'<0 | mi(`var')
}

/* Winzorize */
foreach var in psyc docvisit specdoc medphyc inpat outpat er {
qui sum `var' if `var'>0 & !mi(`var'), d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

gcollapse (mean) psyc firstpsyc docvisit specdoc medphyc inpat outpat er koen, by(pnrg distyrm treatagec tyrm yrm) fast

egen distg=group(distyrm)
egen yrmg=group(yrm)
g byte postreform=(tyrm>=2008.25) & !mi(tyrm)

/** Create postshock dummies **/
sum distg 
global max=r(max)
global maxm1=r(max)-1

sum distg if distyrm==0
global base=r(max)-1

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

compress

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

/**** RD in time  ****/
g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen tyrmg=group(tyrm)

sum tyrmg if tyrm==2008.25
global tyrm0=r(mean)
sum tyrmg
global tyrmmax=r(max)

/*** Create table ***/
mat X=J(8,12,.)
mat stars=J(8,12,0)

preserve
keep if inrange(treatagec,18,27.99)
keep if !inrange(tyrm,2008,2008.25)


* Baseline *
foreach var in firstpsyc docvisit specdoc medphyc inpat outpat er  {
	foreach g in 1 2 {

	qui reg `var' c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if koen==`g'
	
	global b_RDtime_`var'_`g'=0
	forvalues y=20/48 {
	global b_RDtime_`var'_`g'=${b_RDtime_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* First stage *
local j=1
local i=1
foreach g in 1 2 {

* Estimate 
aregben firstpsyc i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if koen==`g', absorb(pnrg) vce(cluster pnr)
mat V=e(V)
mat b=e(b)
mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
global se=sqrt(se[1,1])

global firststage=0
forvalues y=20/48 {
global firststage=${firststage}+_b[`y'.distgpoolpre#1.above]
}

mat X[`i',`j']=${firststage}*3*100
mat X[`i',`j'+1]=${b_RDtime_firstpsyc_`g'}*100
mat X[`i',`j'+2]=${se}*3*100
mat stars[`i',`j']=(abs(${firststage}/${se})>1.645)+(abs(${firststage}/${se})>1.96) + (abs(${firststage}/${se})>2.58)

local j=`j'+3
}

* Second stage *
local j=1
foreach g in 1 2 {

	local i=2
	foreach var in docvisit specdoc medphyc inpat outpat er {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if koen==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global se=sqrt(se[1,1])
	mat est=b[1,"20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	local ttest=est[1,1]/${se}
	
	mat X[`i',`j']=est[1,1]
	mat X[`i',`j'+2]=${se}
	mat stars[`i',`j']=(abs(`ttest')>1.645)+(abs(`ttest')>1.96) + (abs(`ttest')>2.58)

	mat X[`i',`j'+1]=${b_RDtime_`var'_`g'}

	local i=`i'+1
	}
	
local j=`j'+3
}
restore

/** RD 37 **/
keep if inrange(tyrm,2008.25,2012.25)
drop if treatagec==38

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

* Baseline *
foreach var in firstpsyc docvisit specdoc medphyc inpat outpat er  {
	foreach g in 1 2 {

	qui reg `var' c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if koen==`g'

	global b_RD_`var'_`g'=0
	forvalues y=20/48 {
	global b_RD_`var'_`g'=${b_RD_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* First stage *
local j=7
local i=1
foreach g in 1 2 {

* Estimate 
aregben firstpsyc i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if koen==`g', absorb(pnrg) vce(cluster pnr)
mat V=e(V)
mat b=e(b)
mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
global se=sqrt(se[1,1])

global firststage=0
forvalues y=20/48 {
global firststage=${firststage}+_b[`y'.distgpoolpre#1.above]
}

mat X[`i',`j']=${firststage}*3*100
mat X[`i',`j'+1]=${b_RD_firstpsyc_`g'}*100
mat X[`i',`j'+2]=${se}*3*100
mat stars[`i',`j']=(abs(${firststage}/${se})>1.645)+(abs(${firststage}/${se})>1.96) + (abs(${firststage}/${se})>2.58)

local j=`j'+3
}

* Second stage *
local j=7
foreach g in 1 2 {

	local i=2
	foreach var in docvisit specdoc medphyc inpat outpat er {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if koen==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global se=sqrt(se[1,1])
	mat est=b[1,"20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	local ttest=est[1,1]/${se}
	
	mat X[`i',`j']=est[1,1]*3
	mat X[`i',`j'+2]=${se}*3
	mat stars[`i',`j']=(abs(`ttest')>1.645)+(abs(`ttest')>1.96) + (abs(`ttest')>2.58)

	mat X[`i',`j'+1]=${b_RD_`var'_`g'}

	local i=`i'+1
	}
	
local j=`j'+3
}


frmttable using "I:\workdata\706727\Figs\LabormarketTable_BothMeth_Final_ByGender.tex", tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c)  ///
ctitle("Method","RD-DID", " ", "RD", " " \ "Age range", "18-25"," ", "37", " " \ "Gender", "Men", "Women", "Men", "Women")   ///
sdec(2) rtitle("Psychologist (share)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" )

frmttable using "I:\workdata\706727\Figs\LabormarketTable_BothMeth_Final_ByGender.rtf",   replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c) ///
ctitle("Method","RD-DID", " ", "RD", " " \ "Age range", "18-25"," ", "37", " " \ "Gender", "Men", "Women", "Men", "Women")   ///
sdec(2) rtitle("Psychologist (share)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" )


/*********************/
/********* 20 ********/
/*********************/

/**** Data Preb estimates ****/
clear 
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,18,50)
keep if inrange(distyrm,-5,7)

keep pnr dupli distyrm koen inc treatagec tyrm yrm year agec docvisit specdoc medphyc inpat outpat er psyc Dpsyc firstpsyc 

gen koen0=koen if distyrm==0
bysort pnr dupli: egen maxkoen=max(koen0)
replace koen=maxkoen
drop maxkoen koen0

/* Merge with parental income ten years prior */
rename year year2
gen year=year2-5
merge m:1 pnr year using incdata, keepusing(pnr year incf incm)

drop if _merge==2
drop year _merge 
rename year2 year

egen parinc=rowmean(incf incm) 
drop incf incm

/* Create income measure - parental income for individuals below age 28 */
gen income=parinc if treatagec<28
replace income=inc if treatage>=28

/* Create income ranks */
drop if mi(income)

set seed 112
gen double random=runiform()
replace random=(random-0.5)/_N

/* Use value from year before */
sort pnr dupli
by pnr dupli: gen preinc=income if inrange(distyrm,-2,-1.01)
by pnr dupli: egen maxpreinc=mean(preinc)
replace preinc=maxpreinc
drop  maxpreinc

gen fage=floor(agec)
gen ftyrm=floor(tyrm)

cap drop incrank maxincrank
sort year ftyrm fage koen preinc random
by year ftyrm fage koen: gen double incrank=_n
by year ftyrm fage koen: gen double maxincrank=_N
replace incrank=ceil((((incrank-0.5)/maxincrank)*100+random)/(100/3))

foreach var in psyc docvisit specdoc medphyc inpat outpat er {
replace `var'=0 if `var'<0 | mi(`var')
}

/* Winzorize */
foreach var in psyc docvisit specdoc medphyc inpat outpat er {
qui sum `var' if `var'>0 & !mi(`var'), d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

gcollapse (mean) psyc firstpsyc docvisit specdoc medphyc inpat outpat er koen (max) incrank, by(pnr pnrg distyrm treatagec tyrm yrm) fast

egen distg=group(distyrm)
egen yrmg=group(yrm)
g byte postreform=(tyrm>=2008.25) & !mi(tyrm)

/** Create postshock dummies **/
sum distg 
global max=r(max)
global maxm1=r(max)-1

sum distg if distyrm==0
global base=r(max)-1

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

compress

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

/**** RD in time ****/
g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen tyrmg=group(tyrm)

sum tyrmg if tyrm==2008.25
global tyrm0=r(mean)
sum tyrmg
global tyrmmax=r(max)

/*** Create table ***/
mat X=J(8,18,.)
mat stars=J(8,18,0)

preserve
keep if inrange(treatagec,18,27.99)
keep if !inrange(tyrm,2008,2008.25)

* Baseline *
foreach var in firstpsyc docvisit specdoc medphyc inpat outpat er  {
	foreach g in 1 2 3 {

	qui reg `var' c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if incrank==`g'
	
	global b_RDtime_`var'_`g'=0
	forvalues y=20/48 {
	global b_RDtime_`var'_`g'=${b_RDtime_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* First stage *
local j=1
local i=1
foreach g in 1 2 3 {

* Estimate 
aregben firstpsyc i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if incrank==`g', absorb(pnrg) vce(cluster pnr)
mat V=e(V)
mat b=e(b)
mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
global se=sqrt(se[1,1])

global firststage=0
forvalues y=20/48 {
global firststage=${firststage}+_b[`y'.distgpoolpre#1.above]
}

mat X[`i',`j']=${firststage}*3*100
mat X[`i',`j'+1]=${b_RDtime_firstpsyc_`g'}*100
mat X[`i',`j'+2]=${se}*3*100
mat stars[`i',`j']=(abs(${firststage}/${se})>1.645)+(abs(${firststage}/${se})>1.96) + (abs(${firststage}/${se})>2.58)

local j=`j'+3
}

* Second stage *
local j=1
foreach g in 1 2 3 {

	local i=2
	foreach var in docvisit specdoc medphyc inpat outpat er {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if incrank==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global se=sqrt(se[1,1])
	mat est=b[1,"20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	local ttest=est[1,1]/${se}
	
	mat X[`i',`j']=est[1,1]
	mat X[`i',`j'+2]=${se}
	mat stars[`i',`j']=(abs(`ttest')>1.645)+(abs(`ttest')>1.96) + (abs(`ttest')>2.58)

	mat X[`i',`j'+1]=${b_RDtime_`var'_`g'}

	local i=`i'+1
	}
	
local j=`j'+3
}
restore

/** RD 37 **/
keep if inrange(tyrm,2008.25,2012.25)
drop if treatagec==38

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

* Baseline *
foreach var in firstpsyc docvisit specdoc medphyc inpat outpat er  {
	foreach g in 1 2 3 {

	qui reg `var' c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if incrank==`g'
	
	global b_RD_`var'_`g'=0
	forvalues y=20/48 {
	global b_RD_`var'_`g'=${b_RD_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* First stage *
local j=10
local i=1
foreach g in 1 2 3 {

* Estimate 
aregben firstpsyc i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if incrank==`g', absorb(pnrg) vce(cluster pnr)
mat V=e(V)
mat b=e(b)
mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
global se=sqrt(se[1,1])

global firststage=0
forvalues y=20/48 {
global firststage=${firststage}+_b[`y'.distgpoolpre#1.above]
}

mat X[`i',`j']=${firststage}*3*100
mat X[`i',`j'+1]=${b_RD_firstpsyc_`g'}*100
mat X[`i',`j'+2]=${se}*3*100
mat stars[`i',`j']=(abs(${firststage}/${se})>1.645)+(abs(${firststage}/${se})>1.96) + (abs(${firststage}/${se})>2.58)

local j=`j'+3
}

* Second stage *
local j=10
foreach g in 1 2 3 {

	local i=2
	foreach var in docvisit specdoc medphyc inpat outpat er {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if incrank==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global se=sqrt(se[1,1])
	mat est=b[1,"20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	local ttest=est[1,1]/${se}
	
	mat X[`i',`j']=est[1,1]*3
	mat X[`i',`j'+2]=${se}*3
	mat stars[`i',`j']=(abs(`ttest')>1.645)+(abs(`ttest')>1.96) + (abs(`ttest')>2.58)

	mat X[`i',`j'+1]=${b_RD_`var'_`g'}

	local i=`i'+1
	}
	
local j=`j'+3
}

frmttable using "I:\workdata\706727\Figs\LabormarketTable_BothMeth_Final_ByInc.tex", tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c)  ///
ctitle("Method","RD in time", " ", " ", "RD", " ", " " \ "Age range", "18-27"," "," ", "37", " "," " \ "Income tercile", "1st", "2nd","3rd","1st", "2nd","3rd")   ///
sdec(2) rtitle("Psychologist (share)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" )

frmttable using "I:\workdata\706727\Figs\LabormarketTable_BothMeth_Final_ByInc.rtf",   replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c) ///
ctitle("Method","RD in time", " ", " ", "RD", " ", " " \ "Age range", "18-27"," "," ", "37", " "," " \ "Income tercile", "1st", "2nd","3rd","1st", "2nd","3rd")   ///
sdec(2) rtitle("Psychologist (share)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" )


/*********************/
/********* 21 ********/
/*********************/

clear 
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,18,50)
keep if inrange(distyrm,-5,7)

keep pnr famany_fam dupli distyrm treatagec tyrm yrm agec docvisit specdoc medphyc inpat outpat er psyc Dpsyc firstpsyc 

gen famanypre=famany_fam if inrange(distyrm,-2,-1.01) /* Mental illness in the family - same criterion as in MHC results */
bysort pnr dupli: egen famanypremax=max(famanypre)
replace famany_fam=famanypremax
drop famanypre famanypremax

foreach var in psyc docvisit specdoc medphyc inpat outpat er {
replace `var'=0 if `var'<0 | mi(`var')
}

/* Winzorize */
foreach var in psyc docvisit specdoc medphyc inpat outpat er {
qui sum `var' if `var'>0 & !mi(`var'), d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

gcollapse (mean) psyc firstpsyc docvisit specdoc medphyc inpat outpat er (max) famany_fam, by(pnrg distyrm treatagec tyrm yrm) fast

g byte treat=(inrange(treatagec,18,37.99))

egen distg=group(distyrm)
egen yrmg=group(yrm)
g byte postreform=(tyrm>=2008.25) & !mi(tyrm)

/** Create postshock dummies **/
sum distg 
global max=r(max)
global maxm1=r(max)-1

sum distg if distyrm==0
global base=r(max)-1

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

compress

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

/**** RD in time ****/
g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen tyrmg=group(tyrm)

sum tyrmg if tyrm==2008.25
global tyrm0=r(mean)
sum tyrmg
global tyrmmax=r(max)

/*** Create table ***/
mat X=J(8,12,.)
mat stars=J(8,12,0)

preserve
keep if inrange(treatagec,18,27.99)
keep if !inrange(tyrm,2008,2008.25)

* Baseline *
foreach var in firstpsyc docvisit specdoc medphyc inpat outpat er  {
	foreach g in 0 1 {

	qui reg `var' c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if famany_fam==`g'

	global b_RDtime_`var'_`g'=0
	forvalues y=20/48 {
	global b_RDtime_`var'_`g'=${b_RDtime_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* First stage *
local j=1
local i=1
foreach g in 0 1 {

* Estimate 
aregben firstpsyc i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if famany_fam==`g', absorb(pnrg) vce(cluster pnr)
mat V=e(V)
mat b=e(b)
mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
global se=sqrt(se[1,1])

global firststage=0
forvalues y=20/48 {
global firststage=${firststage}+_b[`y'.distgpoolpre#1.above]
}

mat X[`i',`j']=${firststage}*3*100
mat X[`i',`j'+1]=${b_RDtime_firstpsyc_`g'}*100
mat X[`i',`j'+2]=${se}*3*100
mat stars[`i',`j']=(abs(${firststage}/${se})>1.645)+(abs(${firststage}/${se})>1.96) + (abs(${firststage}/${se})>2.58)

local j=`j'+3
}

* Second stage *
local j=1
foreach g in 0 1 {

	local i=2
	foreach var in docvisit specdoc medphyc inpat outpat er {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if famany_fam==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global se=sqrt(se[1,1])
	mat est=b[1,"20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	local ttest=est[1,1]/${se}
	
	mat X[`i',`j']=est[1,1]
	mat X[`i',`j'+2]=${se}
	mat stars[`i',`j']=(abs(`ttest')>1.645)+(abs(`ttest')>1.96) + (abs(`ttest')>2.58)

	mat X[`i',`j'+1]=${b_RDtime_`var'_`g'}

	local i=`i'+1
	}
	
local j=`j'+3
}
restore

/** RD 37 **/
keep if inrange(tyrm,2008.25,2012.25)
drop if treatagec==38

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

* Baseline *
foreach var in firstpsyc docvisit specdoc medphyc inpat outpat er  {
	foreach g in 0 1 {

	qui reg `var'  c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if famany_fam==`g'

	global b_RD_`var'_`g'=0
	forvalues y=20/48 {
	global b_RD_`var'_`g'=${b_RD_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* First stage *
local j=7
local i=1
foreach g in 0 1 {

* Estimate 
aregben firstpsyc i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if famany_fam==`g', absorb(pnrg) vce(cluster pnr)
mat V=e(V)
mat b=e(b)
mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
global se=sqrt(se[1,1])

global firststage=0
forvalues y=20/48 {
global firststage=${firststage}+_b[`y'.distgpoolpre#1.above]
}

mat X[`i',`j']=${firststage}*3*100
mat X[`i',`j'+1]=${b_RD_firstpsyc_`g'}*100
mat X[`i',`j'+2]=${se}*3*100
mat stars[`i',`j']=(abs(${firststage}/${se})>1.645)+(abs(${firststage}/${se})>1.96) + (abs(${firststage}/${se})>2.58)

local j=`j'+3
}

* Second stage *
local j=7
foreach g in 0 1 {

	local i=2
	foreach var in docvisit specdoc medphyc inpat outpat er {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if famany_fam==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global se=sqrt(se[1,1])
	mat est=b[1,"20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	local ttest=est[1,1]/${se}
	
	mat X[`i',`j']=est[1,1]*3
	mat X[`i',`j'+2]=${se}*3
	mat stars[`i',`j']=(abs(`ttest')>1.645)+(abs(`ttest')>1.96) + (abs(`ttest')>2.58)

	mat X[`i',`j'+1]=${b_RD_`var'_`g'}

	local i=`i'+1
	}
	
local j=`j'+3
}

frmttable using "I:\workdata\706727\Figs\LabormarketTable_BothMeth_Final_ByFamMH.tex", tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c)  ///
ctitle("Method","RD in time", " ", "RD", " " \ "Age range", "18-27"," ", "37", " " \ "Family history of mental illness", "No", "Yes","No", "Yes")    ///
sdec(2) rtitle("Psychologist (share)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" )

frmttable using "I:\workdata\706727\Figs\LabormarketTable_BothMeth_Final_ByFamMH.rtf",   replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c) ///
ctitle("Method","RD in time", " ", "RD", " " \ "Age range", "18-27"," ", "37", " " \ "Family history of mental illness", "No", "Yes","No", "Yes")    ///
sdec(2) rtitle("Psychologist (share)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" )


/*********************/
/********* 22 ********/
/*********************/

/**** RD-in-Time Estimates ****/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,21,27.99)
keep if inrange(distyrm,-3.5,7)

** drop individuals just before cutoff ** 
drop if inrange(tyrm,2008,2008.25)

keep pnr dupli koen distyrm treatagec tyrm yrm agec firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp

drop if agec<=18

gen koen0=koen if distyrm==0
bysort pnr dupli: egen maxkoen=max(koen0)
replace koen=maxkoen
drop maxkoen koen0

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
gen tyrm2=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm2

keep if inrange(distyrm,-2.75,7)
gcollapse (mean) firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp, by(pnr pnrg distyrm treatagec tyrm yrm koen) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen distg=group(distyrm)
egen yrmg=group(yrm)
egen tyrmg=group(tyrm)

sum yrmg if yrm==2008.25
global yrm1=r(mean)
global yrm2=r(mean)+1
global yrm3=r(mean)+2
global yrm4=r(mean)+3

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

* Baseline *
foreach var in Ddisab Dsick Dsueduc Dallnonparleave emp {
	foreach g in 1 2 {

	qui reg `var' c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if koen==`g'
	
	global b_RDtime_`var'_`g'=0
	forvalues y=11/39 {
	global b_RDtime_`var'_`g'=${b_RDtime_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* Estimates *
local j=1
foreach g in 1 2 {

	local i=2
	foreach var in Ddisab Dsick Dsueduc Dallnonparleave emp {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if koen==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,39-11+1,1)*V["11.distgpoolpre#1.above".."39.distgpoolpre#1.above","11.distgpoolpre#1.above".."39.distgpoolpre#1.above"]*J(39-11+1,1,1)
	global se_RDtime_`var'_`g'=sqrt(se[1,1])*3
	mat est=b[1,"11.distgpoolpre#1.above".."39.distgpoolpre#1.above"]*J(39-11+1,1,1)
	global est_RDtime_`var'_`g'=est[1,1]*3
	
	local i=`i'+1
	}
	
local j=`j'+3
}

/** RD 37 **/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(tyrm,2008.25,2012.25)
keep if inrange(treatagec,30,47)
keep if inrange(distyrm,-5,7)
drop if treatagec==38

keep pnr dupli koen distyrm treatagec tyrm yrm agec firstpsyc Dpsyc Ddisab Dsick Dallnonparleave emp

gen koen0=koen if distyrm==0
bysort pnr dupli: egen maxkoen=max(koen0)
replace koen=maxkoen
drop maxkoen koen0

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
gen tyrm2=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm2

gcollapse (mean) firstpsyc Dpsyc Ddisab Dsick Dallnonparleave emp , by(pnr pnrg distyrm treatagec tyrm yrm koen) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen distg=group(distyrm)
egen yrmg=group(yrm)

sum yrmg if yrm==2008.25
global yrm1=r(mean)
global yrm2=r(mean)+1
global yrm3=r(mean)+2
global yrm4=r(mean)+3

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

* Baseline *
foreach var in Ddisab Dsick Dallnonparleave emp {
	foreach g in 1 2 {

	qui reg `var'  c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if koen==`g'

	global b_RD_`var'_`g'=0
	forvalues y=20/48 {
	global b_RD_`var'_`g'=${b_RD_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* Estimates *
foreach g in 1 2 {
	foreach var in Ddisab Dsick Dallnonparleave emp {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if koen==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global se_RD_`var'_`g'=sqrt(se[1,1])*3
	mat est=b[1,"20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global est_RD_`var'_`g'=est[1,1]*3
	}
}

/**** Create Table ****/
clear

mat X=J(5,12,.)
mat stars=J(5,12,0)

local i=1
foreach var in  Dsick Ddisab Dsueduc Dallnonparleave emp {
		
	local j=1
	foreach met in RDtime RD  {
			
		foreach g in 1 2 {
		cap mat X[`i',`j']=${est_`met'_`var'_`g'}
		cap mat X[`i',`j'+1]=${b_`met'_`var'_`g'}
		cap mat X[`i',`j'+2]=${se_`met'_`var'_`g'}

		cap mat stars[`i',`j']=(abs(${est_`met'_`var'_`g'}/${se_`met'_`var'_`g'})>1.645)+(abs(${est_`met'_`var'_`g'}/${se_`met'_`var'_`g'})>1.96) + (abs(${est_`met'_`var'_`g'}/${se_`met'_`var'_`g'})>2.58)

		local j=`j'+3
		}
	}
local i=`i'+1
}

frmttable using "I:\workdata\706727\Figs\LabormarketTable_MonthlyLaborOutcomes_ByGender.tex", tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c)  ///
ctitle("Method","RD in time"," ", "RD"," " \ "Age range", "21-27"," ", "37"," " \ "", "Men","Women","Men","Women")   ///
sdec(2) rtitle( "Sick leave"\ "" \ "" \ "Disability pension" \ "" \ "" \ "Under education" \ "" \ "" \ "Any labor market transfer" \ " " \ " " \ "Employment" \ "" \ "")

frmttable using "I:\workdata\706727\Figs\LabormarketTable_MonthlyLaborOutcomes_ByGender.rtf",   replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c) ///
ctitle("Method","RD in time"," ", "RD"," " \ "Age range", "21-27"," ", "37"," " \ "", "Men","Women","Men","Women")   ///
sdec(2) rtitle( "Sick leave"\ "" \ "" \ "Disability pension" \ "" \ "" \ "Under education" \ "" \ "" \ "Any labor market transfer" \ " " \ " " \ "Employment" \ "" \ "")


/*********************/
/********* 23 ********/
/*********************/

/**** RD-in-Time Estimates ****/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,21,27.99)
keep if inrange(distyrm,-3.5,7)

** drop individuals just before cutoff ** 
drop if inrange(tyrm,2008,2008.25)

keep pnr dupli koen distyrm treatagec tyrm yrm year agec firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp

drop if agec<=18

gen koen0=koen if distyrm==0
bysort pnr dupli: egen maxkoen=max(koen0)
replace koen=maxkoen
drop maxkoen koen0

/* Merge with parental income 5 years prior */
rename year year2
gen year=year2-5
merge m:1 pnr year using incdata, keepusing(pnr year incf incm)

drop if _merge==2
drop year _merge 
rename year2 year

egen parinc=rowmean(incf incm) 
drop incf incm

/* Create income ranks */
drop if mi(parinc)

set seed 112
gen double random=runiform()
replace random=(random-0.5)/_N

/* Use value from year before */
sort pnr dupli
by pnr dupli: gen preinc=parinc if inrange(distyrm,-2,-1.01)
by pnr dupli: egen maxpreinc=mean(preinc)
replace preinc=maxpreinc
drop  maxpreinc

gen fage=floor(agec)
gen ftyrm=floor(tyrm)

cap drop incrank maxincrank
sort year ftyrm fage koen preinc random
by year ftyrm fage koen: gen double incrank=_n
by year ftyrm fage koen: gen double maxincrank=_N
replace incrank=ceil((((incrank-0.5)/maxincrank)*100+random)/(100/3))

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
gen tyrm2=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm2

keep if inrange(distyrm,-2.75,7)
gcollapse (mean) firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp (max) incrank , by(pnr pnrg distyrm treatagec tyrm yrm) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen distg=group(distyrm)
egen yrmg=group(yrm)
egen tyrmg=group(tyrm)
sum yrmg if yrm==2008.25
global yrm1=r(mean)
global yrm2=r(mean)+1
global yrm3=r(mean)+2
global yrm4=r(mean)+3

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

* Baseline *
foreach var in Ddisab Dsick Dsueduc Dallnonparleave emp {
	foreach g in 1 2 3 {

	qui reg `var' c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if incrank==`g'
	eststo reg1

	global b_RDtime_`var'_`g'=0
	forvalues y=11/39 {
	global b_RDtime_`var'_`g'=${b_RDtime_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* Estimates *
local j=1
foreach g in 1 2 3 {

	local i=2
	foreach var in Ddisab Dsick Dsueduc Dallnonparleave emp {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if incrank==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,39-11+1,1)*V["11.distgpoolpre#1.above".."39.distgpoolpre#1.above","11.distgpoolpre#1.above".."39.distgpoolpre#1.above"]*J(39-11+1,1,1)
	global se_RDtime_`var'_`g'=sqrt(se[1,1])*3
	mat est=b[1,"11.distgpoolpre#1.above".."39.distgpoolpre#1.above"]*J(39-11+1,1,1)
	global est_RDtime_`var'_`g'=est[1,1]*3
	
	local i=`i'+1
	}
	
local j=`j'+3
}

/** RD 37 **/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(tyrm,2008.25,2012.25)
keep if inrange(treatagec,30,47)
keep if inrange(distyrm,-5,7)

keep pnr dupli inc koen distyrm treatagec tyrm yrm year agec firstpsyc Dpsyc Ddisab Dsick  Dallnonparleave emp

gen koen0=koen if distyrm==0
bysort pnr dupli: egen maxkoen=max(koen0)
replace koen=maxkoen
drop maxkoen koen0

/* Create income ranks */
drop if mi(inc)

set seed 112
gen double random=runiform()
replace random=(random-0.5)/_N

/* Use value from year before */
sort pnr dupli
by pnr dupli: gen preinc=inc if inrange(distyrm,-2,-1.01)
by pnr dupli: egen maxpreinc=mean(preinc)
replace preinc=maxpreinc
drop  maxpreinc

gen fage=floor(agec)
gen ftyrm=floor(tyrm)

cap drop incrank maxincrank
sort year ftyrm fage koen preinc random
by year ftyrm fage koen: gen double incrank=_n
by year ftyrm fage koen: gen double maxincrank=_N
replace incrank=ceil((((incrank-0.5)/maxincrank)*100+random)/(100/3))

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
gen tyrm2=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm2

gcollapse (mean) firstpsyc Dpsyc Ddisab Dsick Dallnonparleave emp (max) incrank , by(pnr pnrg distyrm treatagec tyrm yrm) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen yrmg=group(yrm)
egen distg=group(distyrm)

sum yrmg if yrm==2008.25
global yrm1=r(mean)
global yrm2=r(mean)+1
global yrm3=r(mean)+2
global yrm4=r(mean)+3

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

* Baseline *
foreach var in Ddisab Dsick Dallnonparleave emp {
	foreach g in 1 2 3 {

	qui reg `var'  c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if incrank==`g'

	global b_RD_`var'_`g'=0
	forvalues y=20/48 {
	global b_RD_`var'_`g'=${b_RD_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* Estimates *
foreach g in 1 2 3 {
	foreach var in Ddisab Dsick Dallnonparleave emp {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if incrank==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global se_RD_`var'_`g'=sqrt(se[1,1])*3
	mat est=b[1,"20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global est_RD_`var'_`g'=est[1,1]*3
	}
}

/**** Create Table ****/
clear

mat X=J(5,18,.)
mat stars=J(5,18,0)

local i=1
foreach var in  Dsick Ddisab Dsueduc Dallnonparleave emp {
		
	local j=1
	foreach met in RDtime RD  {
			
		foreach g in 1 2 3 {
		cap mat X[`i',`j']=${est_`met'_`var'_`g'}
		cap mat X[`i',`j'+1]=${b_`met'_`var'_`g'}
		cap mat X[`i',`j'+2]=${se_`met'_`var'_`g'}

		cap mat stars[`i',`j']=(abs(${est_`met'_`var'_`g'}/${se_`met'_`var'_`g'})>1.645)+(abs(${est_`met'_`var'_`g'}/${se_`met'_`var'_`g'})>1.96) + (abs(${est_`met'_`var'_`g'}/${se_`met'_`var'_`g'})>2.58)

		local j=`j'+3
		}
	}
local i=`i'+1
}

frmttable using "I:\workdata\706727\Figs\LabormarketTable_MonthlyLaborOutcomes_ByInc.tex", tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c)  ///
ctitle("Method","RD in time"," "," ", "RD"," "," " \ "Age range", "21-27"," "," ", "37"," "," " \ "Income tercile", "1st", "2nd","3rd", "1st", "2nd","3rd")   ///
sdec(2) rtitle( "Sick leave"\ "" \ "" \ "Disability pension" \ "" \ "" \ "Under education" \ "" \ "" \ "Any labor market transfer" \ " " \ " " \ "Employment" \ "" \ "")

frmttable using "I:\workdata\706727\Figs\LabormarketTable_MonthlyLaborOutcomes_ByInc.rtf",   replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c) ///
ctitle("Method","RD in time"," "," ",  "RD"," "," " \ "Age range", "21-27"," "," ", "37"," "," " \ "Income tercile", "1st", "2nd","3rd", "1st", "2nd","3rd")   ///
sdec(2) rtitle( "Sick leave"\ "" \ "" \ "Disability pension" \ "" \ "" \ "Under education" \ "" \ "" \ "Any labor market transfer" \ " " \ " " \ "Employment" \ "" \ "")


/*********************/
/********* 24 ********/
/*********************/

/**** RD-in-Time Estimates ****/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,21,27.99)
keep if inrange(distyrm,-3.5,7)

** drop individuals just before cutoff ** 
drop if inrange(tyrm,2008,2008.25)

keep pnr dupli famany_fam distyrm treatagec tyrm yrm agec firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp

drop if agec<=18

gen famanypre=famany_fam if inrange(distyrm,-2,-1.01) /* Mental illness in the family - same criterion as in MHC results */
bysort pnr dupli: egen famanypremax=max(famanypre)
replace famany_fam=famanypremax
drop famanypre famanypremax

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
gen tyrm2=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm2

keep if inrange(distyrm,-2.75,7)
gcollapse (mean) firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp (max) famany_fam, by(pnr pnrg distyrm treatagec tyrm yrm) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen distg=group(distyrm)
egen yrmg=group(yrm)
egen tyrmg=group(tyrm)

sum yrmg if yrm==2008.25
global yrm1=r(mean)
global yrm2=r(mean)+1
global yrm3=r(mean)+2
global yrm4=r(mean)+3

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

* Baseline *
foreach var in Ddisab Dsick Dsueduc Dallnonparleave emp {
	foreach g in 0 1 {

	qui reg `var' c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if famany_fam==`g'

	global b_RDtime_`var'_`g'=0
	forvalues y=11/39 {
	global b_RDtime_`var'_`g'=${b_RDtime_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* Estimates *
local j=1
foreach g in 0 1 {

	local i=2
	foreach var in Ddisab Dsick Dsueduc Dallnonparleave emp {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if famany_fam==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,39-11+1,1)*V["11.distgpoolpre#1.above".."39.distgpoolpre#1.above","11.distgpoolpre#1.above".."39.distgpoolpre#1.above"]*J(39-11+1,1,1)
	global se_RDtime_`var'_`g'=sqrt(se[1,1])*3
	mat est=b[1,"11.distgpoolpre#1.above".."39.distgpoolpre#1.above"]*J(39-11+1,1,1)
	global est_RDtime_`var'_`g'=est[1,1]*3
	
	local i=`i'+1
	}
	
local j=`j'+3
}

/** RD 37 **/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(tyrm,2008.25,2012.25)
keep if inrange(treatagec,30,47)
keep if inrange(distyrm,-5,7)

keep pnr dupli famany_fam distyrm treatagec tyrm yrm agec firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp

gen famanypre=famany_fam if inrange(distyrm,-2,-1.01) /* Mental illness in the family - same criterion as in MHC results */
bysort pnr dupli: egen famanypremax=max(famanypre)
replace famany_fam=famanypremax
drop famanypre famanypremax

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
gen tyrm2=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm2

gcollapse (mean) firstpsyc Dpsyc Ddisab Dsick Dsueduc Dallnonparleave emp (max) famany_fam, by(pnr pnrg distyrm treatagec tyrm yrm) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen distg=group(distyrm)
egen yrmg=group(yrm)

sum yrmg if yrm==2008.25
global yrm1=r(mean)
global yrm2=r(mean)+1
global yrm3=r(mean)+2
global yrm4=r(mean)+3

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

* Baseline *
foreach var in Ddisab Dsick Dallnonparleave emp {
	foreach g in 0 1 {

	qui reg `var' c.zabove c.zbelow 1.above  ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${max}.distgpoolpre#1.above [pw=kwt]  if famany_fam==`g'
	eststo reg1

	global b_RD_`var'_`g'=0
	forvalues y=20/48 {
	global b_RD_`var'_`g'=${b_RD_`var'_`g'}+(_b[_cons]+_b[`y'.distg])*3
	}

	}
}

* Estimates *
local j=1
foreach g in 0 1 {
	foreach var in Ddisab Dsick Dallnonparleave emp {
	
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt] if famany_fam==`g', absorb(pnrg) vce(cluster pnr)
	mat V=e(V)
	mat b=e(b)
	mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global se_RD_`var'_`g'=sqrt(se[1,1])*3
	mat est=b[1,"20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global est_RD_`var'_`g'=est[1,1]*3
	}
}

/**** Create Table ****/
clear

mat X=J(5,12,.)
mat stars=J(5,12,0)

local i=1
foreach var in  Dsick Ddisab Dsueduc Dallnonparleave emp {
		
	local j=1
	foreach met in RDtime RD  {
			
		foreach g in 0 1 {
		cap mat X[`i',`j']=${est_`met'_`var'_`g'}
		cap mat X[`i',`j'+1]=${b_`met'_`var'_`g'}
		cap mat X[`i',`j'+2]=${se_`met'_`var'_`g'}

		cap mat stars[`i',`j']=(abs(${est_`met'_`var'_`g'}/${se_`met'_`var'_`g'})>1.645)+(abs(${est_`met'_`var'_`g'}/${se_`met'_`var'_`g'})>1.96) + (abs(${est_`met'_`var'_`g'}/${se_`met'_`var'_`g'})>2.58)

		local j=`j'+3
		}
	}
local i=`i'+1
}

frmttable using "I:\workdata\706727\Figs\LabormarketTable_MonthlyLaborOutcomes_ByFamMH.tex", tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c)  ///
ctitle("Method","RD in time"," ", "RD"," " \ "Age range", "21-27"," ", "37"," " \ "Family history of mental illness", "No", "Yes","No", "Yes")   ///
sdec(2) rtitle( "Sick leave"\ "" \ "" \ "Disability pension" \ "" \ "" \ "Under education" \ "" \ "" \ "Any labor market transfer" \ " " \ " " \ "Employment" \ "" \ "")

frmttable using "I:\workdata\706727\Figs\LabormarketTable_MonthlyLaborOutcomes_ByFamMH.rtf",   replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c) ///
ctitle("Method","RD in time"," ", "RD"," " \ "Age range", "21-27"," ", "37"," " \ "Family history of mental illness", "No", "Yes","No", "Yes")   ///
sdec(2) rtitle( "Sick leave"\ "" \ "" \ "Disability pension" \ "" \ "" \ "Under education" \ "" \ "" \ "Any labor market transfer" \ " " \ " " \ "Employment" \ "" \ "")


/*********************/
/********* 25 ********/
/*********************/

***** Bootstrap standard errors to account for pre-estimation of pre-trends *****

clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_YearCollapse

keep if inrange(year,2000,2011)
keep if minagec>18 & maxagec<50 & !mi(minagec) & !mi(maxagec) 
drop if minagec<=38 & maxagec>=38

/* Generate variables */
replace firstpsykhosp=firstpsykhospAnxDep*100

cap drop treat
gen treat=(minagec>18 & maxagec<38)

cap drop post
gen post=inrange(year,2008,2011)

keep pnr year treat post firstpsykhosp

* Estimation *
cap postclose john
postfile john it year koef using "I:\Workdata\706727\Figs\DID_Illu_Bootstrap" ,replace

forvalues it= 1/500 {
preserve
set seed `it'
bsample , cluster(pnr)

* Detrend *
qui reg firstpsykhosp c.year c.year#1.treat 1.treat if year<2008 

cap drop res
predict res,r

* Estimate Difference *
qui reg res ibn.year ibn.year#1.treat , vce(cluster pnr)

forvalues yr=2000/2011 {
post john (`it')  (`yr') (_b[`yr'.year#1.treat]) 
}
	
restore
}	 
postclose john
*/

* Create standard errors *
clear all
use "I:\Workdata\706727\Figs\DID_Illu_Bootstrap"

forvalues yr=2000/2011 {
sum koef if year==`yr'
global se_DID_`yr'=r(sd)
}

* Standard error of overall DID estimate */
clear 
use "I:\Workdata\706727\Figs\DID_Treatment_Bootstrap"

sum koef if ageg==0 & var=="firstpsykhospAnxDep"
global se_DID_firstpsykhospAnxDep=r(sd)	


***** Estimates ******
clear 
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_YearCollapse

keep if inrange(year,2000,2011)
keep if minagec>18 & maxagec<50 & !mi(minagec) & !mi(maxagec) 
drop if minagec<=38 & maxagec>=38

/* Generate variables */
cap drop treat
gen treat=(minagec>18 & maxagec<38)

replace firstpsykhosp=firstpsykhospAnxDep*100

/* Illustration of method -  Dif-in-dif */

cap postclose john

postfile john treat year koef lower upper using "I:\Workdata\706727\Figs\Final_FiguresAndTables_DetrendDID" ,replace

* Estimate Raw Split sample *
qui reg firstpsykhosp ibn.year#ibn.treat , noconstant vce(cluster pnr)

foreach t in 0 1 {
	forvalues yr=2000/2011 {
	post john (`t') (`yr') (_b[`yr'.year#`t'.treat]) (_b[`yr'.year#`t'.treat]-1.96*_se[`yr'.year#`t'.treat]) (_b[`yr'.year#`t'.treat]+1.96*_se[`yr'.year#`t'.treat])
	}
}

/* Trends */
qui reg firstpsykhosp c.year if year<2008 & treat==0
forvalues yr=2000/2011 {
post john (2) (`yr') (_b[_cons]+`yr'*_b[c.year]) (.) (.)
}
qui reg firstpsykhosp c.year if year<2008 & treat==1
forvalues yr=2000/2011 {
post john (3) (`yr') (_b[_cons]+`yr'*_b[c.year]) (.) (.)
}


* Detrend *
qui reg firstpsykhosp c.year c.year#1.treat 1.treat if year<2008 

count if !mi(firstpsykhosp) & !mi(year) & !mi(treat) & inrange(year,2008,2011) & treat==1
local tot=r(N)
global avpred=0
forvalues yr=2008/2011 {
count if !mi(firstpsykhosp) & !mi(year) & !mi(treat) & year==`yr' & treat==1
global avpred=${avpred}+(_b[_cons]+ _b[1.treat]+(_b[c.year] + _b[c.year#1.treat])*`yr')*(r(N)/`tot')
}

cap drop res
predict res,r

* Estimate Difference *
qui reg res ibn.year ibn.year#1.treat , vce(cluster pnr)

forvalues yr=2000/2011 {
post john (4)  (`yr') (_b[`yr'.year#1.treat]) (_b[`yr'.year#1.treat]-1.96*${se_DID_`yr'}) (_b[`yr'.year#1.treat]+1.96*${se_DID_`yr'})
}

/* Estimate DiD */
cap drop post
gen post=inrange(year,2008,2011) if inrange(year,2000,2011)

qui reg res 1.post 1.treat 1.post#1.treat , vce(cluster pnr)

forvalues yr=2000/2011 {
post john (5)  (`yr') (_b[1.post#1.treat]) (${se_DID_firstpsykhospAnxDep}) (${avpred}+_b[_cons]+_b[1.post]+_b[1.treat])
}
	
postclose john


/* Create figure */
clear 
cd "I:\Workdata\706727\Figs"
use Final_FiguresAndTables_DetrendDID

keep if year<2012

/* Raw */
twoway (line lower upper year if treat==0 , lcolor(black black) lpattern(dash dash) ) ///
	   (line lower upper year if treat==1 , lcolor(red red) lpattern(dash dash)) ///
	   (connect koef year if treat==0, color(black) mfcolor(white)) (connect koef year if treat==1 , color(red)) ///
	   (line koef year if treat==2 , lcolor(black)  lwidth(*1.5)) (line koef year if treat==3 , lcolor(red) lwidth(*1.5)) ///
,graphregion(color(white)) xline(2008) xlabel(2000(2)2010) xtitle("Year") ytitle("Percent") ///
legend(order(6 "Treatment: age<  38" 5 "Control:      age>=38") ring(0) region(color(white)) pos(11) rows(2) symxsize(huge) symysize(thick)) ///
xscale(titlegap(*4)) yscale(titlegap(*4)) xsize(5) ysize(5)

graph export I:\Workdata\706727\Figs\Final_FiguresAndTables_DIDRaw.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_FiguresAndTables_DIDRaw.eps , replace 

/* Detrended Difference */

qui sum koef if treat==5
global  dires: di %10.3f r(mean)

qui sum lower if treat==5
global  dise: di %10.3f r(mean)

qui sum upper if treat==5
global  dibase: di %10.2f r(mean)

twoway (line lower upper year if treat==4 , lcolor(red red) lpattern(dash dash)) ///
	   (connect koef year if treat==4 , color(red)), ///
graphregion(color(white)) xline(2008) xlabel(2000(2)2010) xtitle("Year") ytitle("Percent") ///
legend(off) text(-0.06 2003.5 "Coefficient:${dires}" "Baseline:  ${dibase}  " "se:             ${dise}", box fcolor(white) lcolor(white))  ///
xscale(titlegap(*6)) yscale(titlegap(*4)) xsize(5) ysize(5)

graph export I:\Workdata\706727\Figs\Final_FiguresAndTables_DIDDIF.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_FiguresAndTables_DIDDIF.eps , replace 


/*********************/
/********* 26 ********/
/*********************/

/* RD-Time--DID */
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(yrm,2000,2012.24)
keep if inrange(agec,17,50)

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1

gen count=1
replace yrm=floor(yrm*4)/4
gcollapse (max) maxagec=agec firstpsyc firstpsykhospAnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui (min) minagec=agec (sum) count, by(pnr yrm) fast

keep if minagec>18 & maxagec<50 & !mi(minagec) & !mi(maxagec) 
drop if minagec<=38 & maxagec>=38

cap drop treat
gen treat=(minagec>18 & maxagec<38)

foreach var in firstpsyc firstpsykhospAnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui  {
replace `var'=`var'*100*4
}

drop if mi(pnr) | mi(yrm)

cap drop quarter
gen quarter=round((yrm-floor(yrm))*4+1)


cap drop post dist kwt
g byte post=(yrm>=2008.25) 
g double dist=yrm-2008.25
g double kwt=max(0,2-abs(dist))

cap drop ageg
gen ageg=1 if minagec>=18 & maxagec<28
replace ageg=2 if maxagec>=28 & maxagec<38


foreach var in firstpsyc firstpsykhospAnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui  {

if ("`var'"=="firstadep" | "`var'"=="firstadep") {
local rest "if inrange(yrm,2000,2010)"
local rest2 "& inrange(yrm,2000,2010)"
}
if ("`var'"!="firstadep" & "`var'"!="firstadep") {
local rest2 ""
}

	forvalues a=1/2 {
	qui reg `var' c.dist c.dist#1.post 1.post 1.treat i.quarter i.quarter#1.treat (c.dist c.dist#1.post 1.post)#1.treat [pw=kwt] if (ageg==`a' | treat==0) `rest2' , vce(cluster pnr)

	global est_RDTimeDID_A`a'_`var'=_b[1.post#1.treat]
	global se_RDTimeDID_A`a'_`var'=_se[1.post#1.treat]
	}  
}


/* DID Estimates */

* Estimate standard errors using bootstrap *
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_YearCollapse

keep if inrange(year,2000,2011)
keep if minagec>18 & maxagec<50 & !mi(minagec) & !mi(maxagec) 
drop if minagec<=38 & maxagec>=38

/* Generate variables */
foreach var in firstpsyc firstpsykhospAnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui  {
replace `var'=`var'*100
}

cap drop treat
gen treat=(minagec>18 & maxagec<38)

cap drop post
gen post=inrange(year,2008,2011)

cap drop ageg
gen ageg=1 if minagec>=18 & maxagec<28
replace ageg=2 if maxagec>=28 & maxagec<38

keep pnr year ageg treat post firstpsyc firstpsykhospAnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui

* Estimation *
cap postclose john
postfile john ageg it str30 var koef using "I:\Workdata\706727\Figs\DID_Treatment_Bootstrap" ,replace

forvalues it= 1/500 {
preserve
set seed `it'
bsample , cluster(pnr)

	foreach var in firstpsyc firstpsykhospAnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui  {
	if ("`var'"=="firstadep" | "`var'"=="firstadep") {
	local rest2 "& inrange(yrm,2000,2010)"
	}
	if ("`var'"!="firstadep" & "`var'"!="firstadep") {
	local rest2 ""
	}
	
		/* By age */
		forvalues ageg=1/2 {
		qui reg `var' c.year c.year#1.treat 1.treat if year<2008 & (ageg==`ageg' | treat==0) `rest2'

		cap drop res
		predict res if (ageg==`ageg' | treat==0) `rest2', r

		qui reg res 1.post 1.treat 1.post#1.treat if (ageg==`ageg' | treat==0) `rest2'

		post john (`ageg') (`it') ("`var'") (_b[1.post#1.treat]) 
		}
	}
restore
di `it'
}	 
postclose john

* Create standard errors *
clear all
use "I:\Workdata\706727\Figs\DID_Treatment_Bootstrap"

foreach var in firstpsyc firstpsykhospAnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui {
	forvalues ageg=1/2 {
	sum koef if ageg==`ageg' & var=="`var'"
	global se_DID_A`ageg'_`var'=r(sd)
	}
}

* Estimates * 
clear 
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_YearCollapse

keep if inrange(year,2000,2011)
keep if minagec>18 & maxagec<50 & !mi(minagec) & !mi(maxagec) 
drop if minagec<=38 & maxagec>=38

/* Generate variables */
cap drop treat
gen treat=(minagec>18 & maxagec<38)

foreach var in firstpsyc firstpsykhospAnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui {
replace `var'=`var'*100
}

/* Estimate DID-coefficient */
cap drop post
gen post=inrange(year,2008,2011)

cap drop ageg
gen ageg=1 if minagec>=18 & maxagec<28
replace ageg=2 if maxagec>=28 & maxagec<38

foreach var in firstpsyc firstpsykhospAnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui {
if ("`var'"=="firstadep" | "`var'"=="firstadep") {
local rest2 "& inrange(yrm,2000,2010)"
}
if ("`var'"!="firstadep" & "`var'"!="firstadep") {
local rest2 ""
}

	forvalues ageg=1/2 {

	/* Reduced form */
	qui reg `var' c.year c.year#1.treat 1.treat if year<2008 & (ageg==`ageg' | treat==0) `rest2'

	count if !mi(`var') & !mi(year) & !mi(treat) & inrange(year,2008,2011) & ageg==`ageg' `rest2'
	local tot=r(N)
	global avpred=0
	forvalues yr=2008/2011 {
	count if !mi(`var') & !mi(year) & !mi(treat) & year==`yr' & ageg==`ageg' `rest2'
	global avpred=${avpred}+(_b[_cons]+ _b[1.treat]+(_b[c.year] + _b[c.year#1.treat])*`yr')*(r(N)/`tot')
	}

	cap drop res
	predict res, r

	qui reg res 1.post 1.treat 1.post#1.treat if (ageg==`ageg' | treat==0) `rest2' , vce(cluster pnr)

	global est_DID_A`ageg'_`var'=_b[1.post#1.treat]
	global b_DID_A`ageg'_`var'=${avpred}+_b[_cons]+_b[1.post]+_b[1.treat]

	}
}


/* Create table */
clear

mat X=J(8,8,.)
mat stars=J(8,8,0)

local j=1
foreach met in RDTimeDID_A1 DID_A1 RDTimeDID_A2 DID_A2  {
	
	local i=1
foreach var in firstpsyc firstpsykhospAnxDep firstpsychiatry firsttherapy firstpsyk_test firstadep firstanxsleep firstsui {
	
	mat X[`i',`j']=${est_`met'_`var'}
	mat X[`i',`j'+2]=${se_`met'_`var'}
	
	mat stars[`i',`j']=(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.645)+(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.96) + (abs(${est_`met'_`var'}/${se_`met'_`var'})>2.58)
	
	local i=`i'+1
	}
local j=`j'+3
}

frmttable using I:\workdata\706727\Figs\Final_FiguresAndTables_AlternativeModels_MentalHealth.tex, tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ (,)) basefont(fs12) statfont(fs11) coljust(l c) ///
ctitle("Age range",  "18-27", " ", "28-37", " " \ "Method","RD-Time--DID", "DID" , "RD-Time--DID", "DID" )   ///
sdec(3) ///
rtitle("Psychologist" \ "" \ "Psychiatric hospital" \ "" \ "" \"Psychiatrist"  \ "" \"PCP MHC" \ "" \"PCP Psych. test" \" " \ "Antidepressants" \" " \ "Anxiety and tranquilizers" \" " \ "Suicide attempts" \" "  ) ///
multicol(1,2,2)

frmttable using I:\workdata\706727\Figs\Final_FiguresAndTables_AlternativeModels_MentalHealth.rtf, replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,)) basefont(fs12) statfont(fs11)  coljust(l c) ///
ctitle("Age range",  "18-27", " ", "28-37", " " \ "Method","RD-Time--DID", "DID" , "RD-Time--DID", "DID" )   ///
sdec(3) ///
rtitle("Psychologist" \ "" \ "Psychiatric hospital" \ "" \ "" \"Psychiatrist"  \ "" \"PCP MHC" \ "" \"PCP Psych. test" \" " \ "Antidepressants" \" " \ "Anxiety and tranquilizers" \" " \ "Suicide attempts" \" "  ) ///
multicol(1,2,2)


/*********************/
/********* 27 ********/
/*********************/

/**** Data Preb estimates ****/
clear 
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(tyrm,2005.25,2012.25)
keep if inrange(treatagec,15,50)
keep if inrange(distyrm,-5,7)

keep pnr dupli distyrm treatagec tyrm yrm agec docvisit specdoc medphyc inpat outpat er psyc Dpsyc firstpsyc 

foreach var in psyc docvisit specdoc medphyc inpat outpat er {
replace `var'=0 if `var'<0 | mi(`var')
}

/* Winzorize */
foreach var in psyc docvisit specdoc medphyc inpat outpat er {
qui sum `var' if `var'>0 & !mi(`var'), d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

gcollapse (mean) psyc firstpsyc docvisit specdoc medphyc inpat outpat er, by(pnr pnrg distyrm treatagec tyrm yrm) fast

gen ageg=1 if inrange(treatagec,18,28)
replace ageg=2 if inrange(treatagec,28,38)
replace ageg=3 if inrange(treatagec,38,50) /* Control group */

g byte treat=(inrange(treatagec,18,37.99))

egen distg=group(distyrm)
egen yrmg=group(yrm)
g byte postreform=(tyrm>=2008.25) & !mi(tyrm)

/** Create postshock dummies **/

sum distg 
global max=r(max)
global maxm1=r(max)-1

sum distg if distyrm==0
global base=r(max)-1

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap drop bgdistg2
gen bgdistg2=distg
replace bgdistg2=${max} if distg==${base}
replace bgdistg2=${base} if distg==${max}

* Find cumulative treatment on individual-level *
gen psyc1=(firstpsyc>0 & !mi(firstpsyc)) if !mi(firstpsyc)
cap drop maxfirstpsyc maxmaxfirstpsyc
bysort pnrg: egen maxfirstpsyc=max(psyc1) if distg>20 & distg<28
by pnrg: egen maxmaxfirstpsyc=max(maxfirstpsyc)

compress

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

/**** RD DID ****/

* Standard errors *
preserve
clear 
use "I:\Workdata\706727\Figs\PsykTestLongRun_PooledTable_FullPerDist_RDDID_Bootstrap"

bysort it var: egen sumkoef=sum(koef)

keep it var sumkoef
duplicates drop

gen temp=sumkoef if var=="firstpsyc"
bysort it: egen firststage=max(temp)
	
gen secondstage=sumkoef/firststage

sum sumkoef if  var=="firstpsyc"
global sefirstpsyc=r(sd)

* Second stage *
foreach var in  psyc docvisit specdoc medphyc inpat outpat er   {

sum secondstage if var=="`var'"
global se`var'=r(sd)
}
restore

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=treatagec-18
g byte above=(treatagec>18) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,2.5-abs(d))

mat X=J(8,9,.)
mat stars=J(8,9,0)

* Baseline *
foreach var in firstpsyc docvisit specdoc medphyc inpat outpat er  {
		
qui reg `var' (c.zabove c.zbelow 1.above)##1.postreform  ib${base}.distg ib${base}.distg#c.zabove ib${base}.distg#c.zbelow  ib${base}.distg#c.zabove#1.postreform ib${base}.distg#c.zbelow#1.postreform   ib${base}.distg#1.above  ib${base}.distg#1.postreform  ib${max}.distgpoolpre#1.above#1.postreform [pw=kwt]  if treatage!=18

global b_RDDID_`var'=0
forvalues y=20/48 {
global b_RDDID_`var'=${b_RDDID_`var'} +(_b[_cons] +_b[1.above] +_b[1.postreform]+_b[`y'.distg]+_b[`y'.distg#1.above]+_b[`y'.distg#1.postreform])*3	
}
}

* First stage *
local j=1
local i=1
aregben firstpsyc i.yrmg i.yrmg#1.postreform ib${base}.bgdistg ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  ib${base}.bgdistg#c.zabove#1.postreform ib${base}.bgdistg#c.zbelow#1.postreform   ib${base}.bgdistg#1.above  ib${base}.bgdistg#1.postreform  ib${max}.distgpoolpre#1.above#1.postreform   [pw=kwt] if treatage!=18, absorb(pnrg) 

eststo reg1

global koeffirstpsyc=0
forvalues y=20/48 {
global koeffirstpsyc=${koeffirstpsyc}+_b[`y'.distgpoolpre#1.above#1.postreform]*3
}

mat X[`i',`j']=${koeffirstpsyc}*100
mat X[`i',`j'+1]=${b_RDDID_firstpsyc}*100
mat X[`i',`j'+2]=${sefirstpsyc}*100
mat stars[`i',`j']=(abs(${koeffirstpsyc}/${sefirstpsyc})>1.645)+(abs(${koeffirstpsyc}/${sefirstpsyc})>1.96) + (abs(${koeffirstpsyc}/${sefirstpsyc})>2.58)

* Number of psychologist services *
local j=1
local i=2
aregben psyc i.yrmg i.yrmg#1.postreform ib${base}.bgdistg ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  ib${base}.bgdistg#c.zabove#1.postreform ib${base}.bgdistg#c.zbelow#1.postreform   ib${base}.bgdistg#1.above  ib${base}.bgdistg#1.postreform  ib${max}.distgpoolpre#1.above#1.postreform   [pw=kwt] if treatage!=18, absorb(pnrg) 
eststo reg1

global koef=0
forvalues y=20/48 {
global koef=${koef}+_b[`y'.distgpoolpre#1.above#1.postreform]*3
}

mat X[`i',`j']=${koef}/${koeffirstpsyc}
mat X[`i',`j'+2]=${sepsyc}
mat stars[`i',`j']=(abs((${koef}/${koeffirstpsyc})/${sepsyc})>1.645)+(abs((${koef}/${koeffirstpsyc}/${sepsyc}))>1.96) + (abs((${koef}/${koeffirstpsyc}/${sepsyc}))>2.58)

* Second stage *
local i=3
local j=1

foreach var in docvisit specdoc medphyc inpat outpat er {

qui aregben `var' i.yrmg i.yrmg#1.postreform ib${base}.bgdistg ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  ib${base}.bgdistg#c.zabove#1.postreform ib${base}.bgdistg#c.zbelow#1.postreform   ib${base}.bgdistg#1.above  ib${base}.bgdistg#1.postreform  ib${max}.distgpoolpre#1.above#1.postreform   [pw=kwt] if treatage!=18, absorb(pnrg) 

global koef`var'=0
forvalues y=20/48 {
global koef`var'=${koef`var'}+_b[`y'.distgpoolpre#1.above#1.postreform]*3
}

mat X[`i',`j']=${koef`var'}/${koeffirstpsyc}
mat X[`i',`j'+2]=${se`var'}
mat stars[`i',`j']=(abs((${koef`var'}/${koeffirstpsyc})/${se`var'})>1.645)+(abs((${koef`var'}/${koeffirstpsyc})/${se`var'})>1.96) + (abs((${koef`var'}/${koeffirstpsyc})/${se`var'})>2.58)

mat X[`i',`j'+1]=${b_RDDID_`var'}

local i=`i'+1
}

/**** DID Estimates ****/

keep if inrange(treatagec,18,50)

* Standard errors *
preserve
clear 
use "I:\Workdata\706727\Figs\PsykTestLongRun_PooledTable_FullPerDist_Bootstrap"

bysort it var ageg: egen sumkoef=sum(koef)

keep it var ageg sumkoef
duplicates drop

gen temp=sumkoef if var=="firstpsyc"
bysort it ageg: egen firststage=max(temp)
	
gen secondstage=sumkoef/firststage


forvalues ageg=1/2 {
sum sumkoef if ageg==`ageg' & var=="firstpsyc"
global sefirstpsyc`ageg'=r(sd)
}

* Second stage *
foreach var in  psyc docvisit specdoc medphyc inpat outpat er   {


	forvalues ageg=1/2 {
	sum secondstage if ageg==`ageg' & var=="`var'"
	global se`var'`ageg'=r(sd)
	}
}
restore

/*** Create table ***/
qui count if distg==${base} & treat==1 & postreform==1
global tot=r(N)

/** Age group shares for baseline probability **/
forvalues a=1/2 {
qui count if distg==${base} & treat==1 & postreform==1 & ageg==`a'
global as`a'=r(N)/${tot}
}

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

/** DID By Age **/

* Baseline *
foreach var in firstpsyc docvisit specdoc medphyc inpat outpat er  {
		
qui reg `var' ib3.ageg##1.postreform  ib${base}.distg  ib${base}.distg#ib3.ageg  ib${base}.distg#1.postreform  ib${max}.distgpoolpre#ib3.ageg#1.postreform 

foreach ageg in 1 2 {
	global b_DID_`var'_`ageg'=0
	forvalues y=20/48 {
	global b_DID_`var'_`ageg'=${b_DID_`var'_`ageg'} +(_b[_cons] +_b[`ageg'.ageg] +_b[1.postreform]+_b[`y'.distg]+_b[`y'.distg#`ageg'.ageg]+_b[`y'.distg#1.postreform])*3	
	}
}
}

* First stage *
local i=1
qui aregben firstpsyc  ibn.yrmg ibn.yrmg#ib3.ageg ibn.yrmg#1.postreform  ib${maxm1}.bgdistg  ib${maxm1}.bgdistg#1.postreform ib${maxm1}.bgdistg#ib3.ageg ib${max}.distgpoolpre#1.postreform#ib3.ageg,  absorb(pnrg) 

local j=4
forvalues ageg=1/2 {

global koeffirstpsyc`ageg'=0
	forvalues y=20/48 {
	global koeffirstpsyc`ageg'=${koeffirstpsyc`ageg'}+_b[`y'.distgpoolpre#1.postreform#`ageg'.ageg]
	}
	
	mat X[`i',`j']=${koeffirstpsyc`ageg'}*3*100
	mat X[`i',`j'+1]=${b_DID_firstpsyc_`ageg'}*3*100
	mat X[`i',`j'+2]=${sefirstpsyc`ageg'}*3*100
	mat stars[`i',`j']=(abs(${koeffirstpsyc`ageg'}/${sefirstpsyc`ageg'})>1.645)+(abs(${koeffirstpsyc`ageg'}/${sefirstpsyc`ageg'})>1.96) + (abs(${koeffirstpsyc`ageg'}/${sefirstpsyc`ageg'})>2.58)
	
local j=`j'+3
}

* Number of psychologist services *
local i=2
qui aregben psyc  ibn.yrmg ibn.yrmg#ib3.ageg ibn.yrmg#1.postreform  ib${maxm1}.bgdistg  ib${maxm1}.bgdistg#1.postreform ib${maxm1}.bgdistg#ib3.ageg ib${max}.distgpoolpre#1.postreform#ib3.ageg,  absorb(pnrg) 

local j=4
forvalues ageg=1/2 {

global koefpsyc`ageg'=0
	forvalues y=20/48 {
	global koefpsyc`ageg'=${koefpsyc`ageg'}+_b[`y'.distgpoolpre#1.postreform#`ageg'.ageg]
	}
	
	mat X[`i',`j']=${koefpsyc`ageg'}/${koeffirstpsyc`ageg'}
	mat X[`i',`j'+2]=${sepsyc`ageg'}
	mat stars[`i',`j']=(abs((${koefpsyc`ageg'}/${koeffirstpsyc`ageg'})/${sepsyc`ageg'})>1.645)+(abs((${koefpsyc`ageg'}/${koeffirstpsyc`ageg'})/${sepsyc`ageg'})>1.96) + (abs((${koefpsyc`ageg'}/${koeffirstpsyc`ageg'})/${sepsyc`ageg'})>2.58)

local j=`j'+3
}

/* Other outcomes */

local i=3
foreach var in  docvisit specdoc medphyc inpat outpat er  {
	
qui aregben `var'  ibn.yrmg ibn.yrmg#ib3.ageg ibn.yrmg#1.postreform  ib${maxm1}.bgdistg  ib${maxm1}.bgdistg#1.postreform ib${maxm1}.bgdistg#ib3.ageg ib${max}.distgpoolpre#1.postreform#ib3.ageg,  absorb(pnrg) 

	local j=4
	forvalues ageg=1/2 {
	global koef`var'`ageg'=0
	forvalues y=20/48 {
	global koef`var'`ageg'=${koef`var'`ageg'}+_b[`y'.distgpoolpre#1.postreform#`ageg'.ageg]
	}

	mat X[`i',`j']=${koef`var'`ageg'}/${koeffirstpsyc`ageg'}
	mat X[`i',`j'+1]=${b_DID_`var'_`ageg'}
	mat X[`i',`j'+2]=${se`var'`ageg'}
	mat stars[`i',`j']=(abs((${koef`var'`ageg'}/${koeffirstpsyc`ageg'})/${se`var'`ageg'})>1.645)+(abs((${koef`var'`ageg'}/${koeffirstpsyc`ageg'})/${se`var'`ageg'})>1.96) + (abs((${koef`var'`ageg'}/${koeffirstpsyc`ageg'})/${se`var'`ageg'})>2.58)

	local j=`j'+3
	}

local i=`i'+1
}


frmttable using "I:\workdata\706727\Figs\LabormarketTable_AltMeth_Final_FullPer.tex", tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c)  ///
ctitle("Method","RD-DID", " ", "DID", \ "Age range", "18", "18-27", "28-37")   ///
sdec(2) rtitle("Psychologist (share)" \ "" \ "" \"Psychologist (services)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" )

frmttable using "I:\workdata\706727\Figs\LabormarketTable_AltMeth_Final_FullPer.rtf",   replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c) ///
ctitle("Method","RD-DID", " ", "DID" \ "Age range", "18", "18-27", "28-37")   ///
sdec(2) rtitle("Psychologist (share)" \ "" \ "" \"Psychologist (services)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" )


/*********************/
/********* 28 ********/
/*********************/

/*** RD-DID 18 ***/
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

keep if inrange(year,2000,2012)

destring(kom),replace
merge m:1 kom year using  "I:\Workdata\706727\Build\Data\ChildhospByKomYear.dta" 
keep if _merge==3
drop _merge

* Same sample as year_collapse *
drop if year==2012 & month>3
keep if inrange(agec,9,30) 

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)

gen byte firstDPHosp_AnxDep=firstpsykhosp*DPHosp_AnxDep==1
gen byte firstDerp_AnxDep=firstpsykhosp*Derp_AnxDep==1
gen byte firstDbamb_AnxDep=firstpsykhosp*Dbamb_AnxDep==1
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep==1

/* Estimates are not directly comparable to DID results */
foreach var in firstpsyc firstpsykhospAnxDep firstadep firstsui {
replace `var'=`var'*100*12
}

cap drop Dyear
gen Dyear=0 if inrange(year,2000,2007) | (year==2008 & month<4)
replace Dyear=1 if inrange(year,2009,2012) | (year==2008 & month>=4)

gen cutoff2006=cutoff if year==2006
bysort kom: egen max=max(cutoff2006)
replace cutoff2006=max
drop max

/* Regression */
gen belowcutoff=(agec<cutoff)

g byte above=(agec>=18) if !mi(agec)
g byte below=(agec<18) if !mi(agec)

g double dist=agec-18
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,2.5-abs(dist))

cap postclose john
postfile john str30 var bw koef lower upper using I:\Workdata\706727\Figs\Final_Robustness_RDDID18_Bandwidth, replace

forvalues bw=1(0.5)8 {
cap drop kwt
g double kwt=max(0,`bw'-abs(dist))

	foreach var in firstpsyc firstpsykhospAnxDep firstadep firstsui {
	reg `var' 1.above c.zabove c.zbelow 1.Dyear i.cutoff#1.belowcutoff i.cutoff  1.Dyear#(1.above c.zabove c.zbelow)  [pw=kwt] if agec!=18 , vce(cluster pnr)
	post john ("`var'") (`bw') (_b[1.Dyear#1.above]) (_b[1.Dyear#1.above]-1.96*_se[1.Dyear#1.above]) (_b[1.Dyear#1.above]+1.96*_se[1.Dyear#1.above])
	}
}
postclose john


/* Create Figure */
clear all
cd "I:\Workdata\706727\Figs"
use Final_Robustness_RDDID18_Bandwidth

twoway (rcap lower upper bw if var=="firstpsyc", color(gs7)) (scatter koef bw if bw!=2.5  & var=="firstpsyc" , mcolor(black) mfcolor(white) msize(medlarge))  ///
		(scatter koef bw if bw==2.5 &  var=="firstpsyc", mcolor(red) msize(medlarge)) , ///		
	    graphregion(color(white))  xsize(4) ysize(5) xtitle("Bandwidth (Age)", size(medlarge)) ytitle("Percentage points", size(medlarge)) xscale(titlegap(*6)) yscale(titlegap(*4)) ///
		legend(order(2 3 1) label(2 "Alternative bandwidth") label(3 "Preferred bandwidth") label(1 "95% CI") ring(0) rows(3) pos(9) region(color(white)) size(medium)) ///
		yline(0, lcolor(black)) ylabel(0(0.2)1,labsize(medlarge))  xlabel(,labsize(medlarge))

graph export I:\Workdata\706727\Figs\Final_Robustness_RDDID18_Bandwidth_Psyc.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Robustness_RDDID18_Bandwidth_Psyc.eps , replace 

twoway (rcap lower upper bw if var=="firstpsykhospAnxDep", color(gs7)) (scatter koef bw if bw!=2.5 & var=="firstpsykhospAnxDep" , mcolor(black) mfcolor(white)  msize(medlarge))  ///
		(scatter koef bw if bw==2.5 &  var=="firstpsykhospAnxDep", mcolor(red) msize(medlarge))  , ///		
	    graphregion(color(white))  xsize(4) ysize(5) xtitle("Bandwidth (Age)", size(medlarge)) ytitle("Percentage points", size(medlarge)) xscale(titlegap(*6)) yscale(titlegap(*4)) ///
		legend(order(2 3 1) label(2 "Alternative bandwidth") label(3 "Preferred bandwidth") label(1 "95% CI") ring(0) rows(3) pos(1) region(color(white)) size(medium)) ///
		yline(0, lcolor(black)) ylabel(,labsize(medlarge)) xlabel(,labsize(medlarge))
		
graph export I:\Workdata\706727\Figs\Final_Robustness_RDDID18_Bandwidth_PsykHosp.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Robustness_RDDID18_Bandwidth_PsykHosp.eps , replace 

twoway (rcap lower upper bw if var=="firstadep", color(gs7)) (scatter koef bw if bw!=2.5 &  var=="firstadep" , mcolor(black) mfcolor(white) msize(medlarge))  ///
		(scatter koef bw if bw==2.5 &  var=="firstadep", mcolor(red) msize(medlarge))   , ///		
	    graphregion(color(white))  xsize(4) ysize(5) xtitle("Bandwidth (Age)", size(medlarge)) ytitle("Percentage points", size(medlarge)) xscale(titlegap(*6)) yscale(titlegap(*4)) ///
		legend(order(2 3 1) label(2 "Alternative bandwidth") label(3 "Preferred bandwidth") label(1 "95% CI") ring(0) rows(3) pos(5) region(color(white)) size(medium)) ///
		yline(0, lcolor(black)) ylabel(,labsize(medlarge)) xlabel(,labsize(medlarge))

graph export I:\Workdata\706727\Figs\Final_Robustness_RDDID18_Bandwidth_Adep.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Robustness_RDDID18_Bandwidth_Adep.eps , replace 

twoway (rcap lower upper bw if var=="firstsui", color(gs7)) (scatter koef bw if bw!=2.5  &  var=="firstsui" , mcolor(black) mfcolor(white) msize(medlarge))  ///
		(scatter koef bw if bw==2.5 &  var=="firstsui", mcolor(red) msize(medlarge))  , ///		
	    graphregion(color(white))  xsize(4) ysize(5) xtitle("Bandwidth (Age)", size(medlarge)) ytitle("Percentage points", size(medlarge)) xscale(titlegap(*6)) yscale(titlegap(*4)) ///
		legend(order(2 3 1) label(2 "Alternative bandwidth") label(3 "Preferred bandwidth") label(1 "95% CI") ring(0) rows(3) pos(5) region(color(white)) size(medium)) ///
		yline(0, lcolor(black)) ylabel(,labsize(medlarge)) xlabel(,labsize(medlarge))

graph export I:\Workdata\706727\Figs\Final_Robustness_RDDID18_Bandwidth_Sui.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Robustness_RDDID18_Bandwidth_Sui.eps , replace 

/*** RD 37 ***/
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_final

keep if inrange(year,2009,2011) | (year==2008 & month>=4) | (year==2012 & month<4)

keep if inrange(agec,20,58)

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep

foreach var in firstpsyc firstpsykhospAnxDep firstadep firstsui {
replace `var'=`var'*100*12
}

preserve
gen john=1
gcollapse (mean) firstpsyc firstpsykhospAnxDep firstadep (count) john, by(agec) fast
 
foreach var in firstpsyc firstpsykhospAnxDep firstadep {

rdbwselect `var' agec if agec!=38, c(38) p(1) weights(john) kernel(tri) masspoints(off)
global bwrt_`var'=round(e(h_mserd),0.5)
}
restore

/* Regression */
cap postclose john
postfile john str30 var bw koef lower upper using I:\Workdata\706727\Figs\Final_Robustness_RD37_Bandwidth, replace

forvalues bw=1(0.5)15 {
cap drop kwt
g double kwt=max(0,`bw'-abs(dist))

	foreach var in firstpsyc firstpsykhospAnxDep firstadep {
	qui reg `var' 1.above c.zabove c.zbelow   [pw=kwt] if  agec!=38, vce(cluster pnr)
	post john ("`var'") (`bw') (_b[1.above]) (_b[1.above]-1.96*_se[1.above]) (_b[1.above]+1.96*_se[1.above])
	}
}
postclose john

/* Create Figure */
clear all
cd "I:\Workdata\706727\Figs"
use Final_Robustness_RD37_Bandwidth

twoway (rcap lower upper bw if var=="firstpsyc", color(gs7)) (scatter koef bw if bw!=7.5  & bw!=${bwrt_firstpsyc} &  var=="firstpsyc" , mcolor(black) mfcolor(white) msize(medlarge))  ///
		(scatter koef bw if bw==7.5 &  var=="firstpsyc", mcolor(red) msize(medlarge))  (scatter koef bw if bw==${bwrt_firstpsyc} &  var=="firstpsyc" , mcolor(green)  msize(medlarge)) , ///		
	    graphregion(color(white))  xsize(3) ysize(5) xtitle("Bandwidth (Age)", size(medlarge)) ytitle("Percentage points", size(medlarge)) xscale(titlegap(*6)) yscale(titlegap(*4)) ///
		legend(order(2 3 4 1) label(2 "Alternative bandwidth") label(3 "Preferred bandwidth")  label(4 "Calonico et al. bandwidth") label(1 "95% CI") ring(0) rows(4) pos(3) region(color(none)) size(medium)) ///
		yline(0, lcolor(black)) ylabel(0(0.2)1,labsize(medlarge))  xlabel(,labsize(medlarge))

graph export I:\Workdata\706727\Figs\Final_Robustness_RD37_Bandwidth_Psyc.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Robustness_RD37_Bandwidth_Psyc.eps , replace 

twoway (rcap lower upper bw if var=="firstpsykhospAnxDep", color(gs7)) (scatter koef bw if bw!=7.5  & bw!=${bwrt_firstpsykhospAnxDep} &  var=="firstpsykhospAnxDep" , mcolor(black) mfcolor(white)  msize(medlarge))  ///
		(scatter koef bw if bw==7.5 &  var=="firstpsykhospAnxDep", mcolor(red) msize(medlarge))  (scatter koef bw if bw==${bwrt_firstpsykhospAnxDep} &  var=="firstpsykhospAnxDep" , mcolor(green)  msize(medlarge)) , ///		
	    graphregion(color(white))  xsize(3) ysize(5) xtitle("Bandwidth (Age)", size(medlarge)) ytitle("Percentage points", size(medlarge)) xscale(titlegap(*6)) yscale(titlegap(*4)) ///
		legend(order(2 3 4 1) label(2 "Alternative bandwidth") label(3 "Preferred bandwidth")  label(4 "Calonico et al. bandwidth") label(1 "95% CI") ring(0) rows(4) pos(1) region(color(white)) size(medium)) ///
		yline(0, lcolor(black)) ylabel(,labsize(medlarge)) xlabel(,labsize(medlarge))
		
graph export I:\Workdata\706727\Figs\Final_Robustness_RD37_Bandwidth_PsykHosp.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Robustness_RD37_Bandwidth_PsykHosp.eps , replace 

twoway (rcap lower upper bw if var=="firstadep", color(gs7)) (scatter koef bw if bw!=7.5  & bw!=${bwrt_firstadep} &  var=="firstadep" , mcolor(black) mfcolor(white) msize(medlarge))  ///
		(scatter koef bw if bw==7.5 &  var=="firstadep", mcolor(red) msize(medlarge))  (scatter koef bw if bw==${bwrt_firstadep} &  var=="firstadep" , mcolor(green)  msize(medlarge)) , ///		
	    graphregion(color(white))  xsize(3) ysize(5) xtitle("Bandwidth (Age)", size(medlarge)) ytitle("Percentage points", size(medlarge)) xscale(titlegap(*6)) yscale(titlegap(*4)) ///
		legend(order(2 3 4 1) label(2 "Alternative bandwidth") label(3 "Preferred bandwidth")  label(4 "Calonico et al.  bandwidth") label(1 "95% CI") ring(0) rows(4) pos(1) region(color(white)) size(medium)) ///
		yline(0, lcolor(black)) ylabel(,labsize(medlarge)) xlabel(,labsize(medlarge))

graph export I:\Workdata\706727\Figs\Final_Robustness_RD37_Bandwidth_Adep.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Robustness_RD37_Bandwidth_Adep.eps , replace 


/*********************/
/********* 29 ********/
/*********************/

/**** RD Time ****/

clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,18,27.99)
keep if inrange(distyrm,-5,7)

keep pnr dupli distyrm treatagec tyrm yrm agec inpat outpat er psyc Dpsyc firstpsyc 

** drop individuals just before cutoff ** 
drop if inrange(tyrm,2008,2008.25)

foreach var in psyc inpat outpat er {
replace `var'=0 if `var'<0 | mi(`var')
}

/* Winzorize */
foreach var in psyc inpat outpat er {
qui sum `var' if `var'>0 & !mi(`var'), d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
}
egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

gcollapse (mean) firstpsyc inpat outpat er , by(pnrg distyrm treatagec tyrm yrm) fast

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

egen distg=group(distyrm)
egen yrmg=group(yrm)
egen tyrmg=group(tyrm)

sum tyrmg if tyrm==2008.25
global tyrm0=r(mean)
sum tyrmg
global tyrmmax=r(max)

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=1
global base=r(max)-${bdist}

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

cap postclose john
postfile john str30 var bw koef lower upper using "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RDintime_Bandwidth", replace

forvalues bw=1(0.5)10 {
cap drop kwt
g double kwt=max(0,`bw'-abs(d))

	foreach var in firstpsyc inpat outpat er {
	    
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zbelow ib${base}.bgdistg#c.zabove ib${base}.distgpoolpre#1.above [pw=kwt], absorb(pnrg)
	
	global koef=0
	forvalues y=20/48 {
	global koef=${koef}+_b[`y'.distgpoolpre#1.above]
	}
	mat V=e(V)
	mat se=J(1,48-20+1,1)*V["20.distgpoolpre#1.above".."48.distgpoolpre#1.above","20.distgpoolpre#1.above".."48.distgpoolpre#1.above"]*J(48-20+1,1,1)
	global se=sqrt(se[1,1])

	post john ("`var'") (`bw') (${koef}) (${koef}-1.96*${se}) (${koef}+1.96*${se}) 
	
	}
}
postclose john


** figure **
clear all
cd "I:\Workdata\706727\Figs"
use Final_PhysicalLabor_Robustness_RDintime_Bandwidth

replace koef=koef*3
replace lower=lower*3
replace upper=upper*3

replace koef=koef*100 if var=="firstpsyc"
replace lower=lower*100 if var=="firstpsyc"
replace upper=upper*100 if var=="firstpsyc"

foreach var in firstpsyc  inpat outpat er {
if ("`var'"=="firstpsyc") {
local ytit "Percentage points"
local tit "Psychologist"
}
if ("`var'"!="firstpsyc") {
local ytit "Number of services"
local ylab "ylabel(-0.4(0.1)0.3,labsize(medium))"
}
if ("`var'"=="er") {
local tit "Emergency room visits"
}
if ("`var'"=="outpat") {
local tit "Outpatient hospital contacts"
}
if ("`var'"=="inpat") {
local tit "Inpatient hospital contacts"
}

twoway (rcap lower upper bw if var=="`var'", color(gs7)) (scatter koef bw if bw!=7.5 &  var=="`var'" , mcolor(black) mfcolor(white)) ///
		(scatter koef bw if bw==7.5 &  var=="`var'", mcolor(red)) , ///		
	    graphregion(color(white))  xsize(5) ysize(5) xtitle("Bandwidth (Age)",size(medium)) ytitle("`ytit'",size(medium)) xscale(titlegap(*6)) yscale(titlegap(*4)) ///
		legend(order(2 3 1) label(2 "Alternative bandwidth") label(3 "Preferred bandwidth") label(1 "95% CI") rows(1) pos(6) region(color(white)) size(small)) ///
		yline(0, lcolor(black))  xlabel(,labsize(medium)) ylabel(,labsize(medium)) name(`var',replace) title("`tit'", size(medium) color(black)) 
}

grc1leg firstpsyc er outpat inpat, iscale(*0.9) graphregion(color(white)) rows(2) legendfrom(firstpsyc) name(john, replace)

graph display john, xsize(10) ysize(12)

graph export "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RDtime_Bandwidth.png" , replace width(2000)
graph export "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RDtime_Bandwidth.eps" , replace 


/**** RD ****/
clear 
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,18,50)
keep if inrange(distyrm,-5,7)

keep pnr dupli distyrm treatagec tyrm yrm agec inpat Dpsyc Ddisab Dsick

replace inpat=0 if inpat<0 | mi(inpat)

/* Winzorize */
qui sum inpat if inpat>0 & !mi(inpat), d
replace inpat=r(p99) if inpat>r(p99) & !mi(inpat)

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
gen tyrm2=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm2

keep if distyrm<2
gcollapse (mean) inpat Dpsyc Ddisab Dsick, by(pnr pnrg distyrm treatagec tyrm yrm) fast

keep if inrange(tyrm,2008.25,2012.25)
keep if inrange(treatagec,30,47)

g byte postshock=(distyrm>=0) & !mi(distyrm)

egen distg=group(distyrm)
egen yrmg=group(yrm)

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=3
global base=r(max)-${bdist}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

** Load slightly different version of areg (only appropriate when clusters nest absorb variable) **
cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

cap postclose john
postfile john str30 var bw koef lower upper using "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RD_Bandwidth", replace

forvalues bw=1(0.5)15 {
cap drop kwt
g double kwt=max(0,`bw'-abs(d))

	foreach var in firstpsyc inpat outpat er {
	    
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  1.postshock#1.above  [pw=kwt] if treatage!=38, vce(cluster pnr) absorb(pnrg)
	post john ("`var'") (`bw') (_b[1.postshock#1.above]) (_b[1.postshock#1.above]-1.96*_se[1.postshock#1.above]) (_b[1.postshock#1.above]+1.96*_se[1.postshock#1.above])
	
	}
}
postclose john

/* Create Figures */

** RD **
clear all
cd "I:\Workdata\706727\Figs"
use Final_PhysicalLabor_Robustness_RD_Bandwidth

replace koef=koef*3*(27-20+1) 
replace lower=lower*3*(27-20+1) 
replace upper=upper*3*(27-20+1) 

replace koef=koef*100 if var=="firstpsyc"
replace lower=lower*100 if var=="firstpsyc"
replace upper=upper*100 if var=="firstpsyc"

foreach var in firstpsyc  inpat outpat er {
if ("`var'"=="firstpsyc") {
local ytit "Percentage points"
local tit "Psychologist"
}
if ("`var'"!="firstpsyc") {
local ytit "Number of services"
local ylab "ylabel(-0.4(0.1)0.3,labsize(medium))"
}
if ("`var'"=="er") {
local tit "Emergency room visits"
}
if ("`var'"=="outpat") {
local tit "Outpatient hospital contacts"
}
if ("`var'"=="inpat") {
local tit "Inpatient hospital contacts"
}

twoway (rcap lower upper bw if var=="`var'", color(gs7)) (scatter koef bw if bw!=7.5 &  var=="`var'" , mcolor(black) mfcolor(white)) ///
		(scatter koef bw if bw==7.5 &  var=="`var'", mcolor(red)) , ///		
	    graphregion(color(white))  xsize(5) ysize(5) xtitle("Bandwidth (Age)",size(medium)) ytitle("`ytit'",size(medium)) xscale(titlegap(*6)) yscale(titlegap(*4)) ///
		legend(order(2 3 1) label(2 "Alternative bandwidth") label(3 "Preferred bandwidth") label(1 "95% CI") rows(1) pos(6) region(color(white)) size(small)) ///
		yline(0, lcolor(black))  xlabel(,labsize(medium)) ylabel(,labsize(medium)) name(`var',replace) title("`tit'", size(medium) color(black)) 
}

grc1leg firstpsyc er outpat inpat, iscale(*0.9) graphregion(color(white)) rows(2) legendfrom(firstpsyc)

graph export "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RD_Bandwidth.png" , replace width(2000)
graph export "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RD_Bandwidth.eps" , replace 


/*********************/
/********* 30 ********/
/*********************/

/*** RD Placebo results ***/
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_final

keep if inrange(year,2009,2011) | (year==2008 & month>=4) | (year==2012 & month<4)

/* Same data as collapse */
keep if inrange(agec,18,58)

/* Generate variables */
gen AnxDep=(Dbamb_AnxDep==1 | Derp_AnxDep==1 | DPHosp_AnxDep==1)
gen byte firstpsykhospAnxDep=firstpsykhosp*AnxDep

foreach var in firstpsyc firstpsykhospAnxDep firstadep firstsui {
replace `var'=`var'*100*12
}


/* Regression */
cap postclose john
postfile john str30 var cutoff koef lower upper using I:\Workdata\706727\Figs\Final_Robustness_RD_OtherDisc, replace

forvalues a=26/52 {

cap drop above below dist zabove zbelow kwt
g byte above=(agec<`a') if !mi(agec)
g byte below=(agec>=`a') if !mi(agec)

g double dist=agec-`a'
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

	foreach var in  firstpsykhospAnxDep firstadep firstpsyc {
	qui reg `var' 1.above c.zabove c.zbelow   [pw=kwt] if agec!=`a', vce(cluster pnr)
	post john ("`var'") (`a') (_b[1.above]) (_b[1.above]-1.96*_se[1.above]) (_b[1.above]+1.96*_se[1.above])
	}

}
postclose john

/* Create Figure */
clear all
cd "I:\Workdata\706727\Figs"
use Final_Robustness_RD_OtherDisc

twoway (rcap lower upper cutoff if var=="firstpsyc", color(gs7)) (scatter koef cutoff if var=="firstpsyc" & cutoff!=38, mcolor(black) mfcolor(white) msize(medlarge)) ///
		(scatter koef cutoff if var=="firstpsyc" & cutoff==38, mcolor(red) msize(medlarge)) , ///		
	    graphregion(color(white))  xsize(5) ysize(5) xtitle("Age", size(medlarge)) ytitle("Percentage points", size(medlarge)) xscale(titlegap(*4)) yscale(titlegap(*4)) ///
		ylabel(-0.6(0.2)0.8, labsize(medlarge)) xlabel(, labsize(medlarge))  ///
		legend(order(2 3 ) label(2 "Placebo estimate") label(3 "Policy estimate") ring(0) rows(2) pos(5) region(color(white)) size(medium)) yline(0, lcolor(black))

graph export I:\Workdata\706727\Figs\Final_Robustness_RD_OtherDisc_Psyc.png, replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Robustness_RD_OtherDisc_Psyc.eps, replace 


twoway (rcap lower upper cutoff if var=="firstpsykhospAnxDep", color(gs7)) (scatter koef cutoff if var=="firstpsykhospAnxDep" & cutoff!=38, mcolor(black) mfcolor(white) msize(medlarge)) ///
		(scatter koef cutoff if var=="firstpsykhospAnxDep" & cutoff==38, mcolor(red) msize(medlarge)) , ///		
	    graphregion(color(white))  xsize(5) ysize(5) xtitle("Age", size(medlarge)) ytitle("Percentage points", size(medlarge)) xscale(titlegap(*4)) yscale(titlegap(*4)) ///
		ylabel(, labsize(medlarge)) xlabel(, labsize(medlarge))  ///
		legend(order(2 3 ) label(2 "Placebo estimate") label(3 "Policy estimate") ring(0) rows(2) pos(5) region(color(white)) size(medium)) yline(0, lcolor(black))

graph export I:\Workdata\706727\Figs\Final_Robustness_RD_OtherDisc_PsykHosp.png, replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Robustness_RD_OtherDisc_PsykHosp.eps, replace 

twoway (rcap lower upper cutoff if var=="firstadep", color(gs7)) (scatter koef cutoff if var=="firstadep" & cutoff!=38, mcolor(black) mfcolor(white) msize(medlarge)) ///
		(scatter koef cutoff if var=="firstadep" & cutoff==38, mcolor(red) msize(medlarge)) , ///		
	    graphregion(color(white))  xsize(5) ysize(5) xtitle("Age", size(medlarge)) ytitle("Percentage points", size(medlarge)) xscale(titlegap(*4)) yscale(titlegap(*4)) ///
		ylabel(-0.15(0.05)0.15, labsize(medlarge)) xlabel(, labsize(medlarge)) ///
		legend(order(2 3 ) label(2 "Placebo estimate") label(3 "Policy estimate") ring(0) rows(2) pos(5) region(color(white)) size(medium)) yline(0, lcolor(black))
		
graph export I:\Workdata\706727\Figs\Final_Robustness_RD_OtherDisc_Adep.png , replace width(2000)
graph export I:\Workdata\706727\Figs\Final_Robustness_RD_OtherDisc_Adep.eps , replace 


/*********************/
/********* 31 ********/
/*********************/

** RD **
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,18,58)
keep if inrange(distyrm,-5,7)

keep pnr dupli distyrm treatagec tyrm yrm agec docvisit specdoc medphyc inpat outpat er psyc Dpsyc firstpsyc 

foreach var in docvisit specdoc medphyc inpat outpat er {
replace `var'=0 if `var'<0 | mi(`var')
}

/* Winzorize */
foreach var in docvisit specdoc medphyc inpat outpat er {
qui sum `var' if `var'>0 & !mi(`var'), d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

keep if distyrm<2
gcollapse (mean) Dpsyc firstpsyc docvisit specdoc medphyc inpat outpat er, by(pnr pnrg distyrm treatagec tyrm yrm) fast

egen distg=group(distyrm)
egen yrmg=group(yrm)

/** Create postshock dummies **/

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=3
global base=r(max)-${bdist}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

keep if inrange(tyrm,2008.25,2012.25)

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"


cap postclose john
postfile john str30 var cutoff koef lower upper using "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RDOtherDisc", replace

forvalues a=26/52 {

cap drop d above zabove zbelow kwt
g double d=treatagec-`a'
g byte above=(treatagec<`a') if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

	foreach var in firstpsyc docvisit specdoc medphyc inpat outpat er {
		
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  1.postshock#1.above  [pw=kwt] if treatage!=`a', vce(cluster pnr) absorb(pnrg)
	
	post john ("`var'") (`a') (_b[1.postshock#1.above]) (_b[1.postshock#1.above]-1.96*_se[1.postshock#1.above]) (_b[1.postshock#1.above]+1.96*_se[1.postshock#1.above])
	}

}
postclose john



/** Figures **/
clear all
cd "I:\Workdata\706727\Figs"
use Final_PhysicalLabor_Robustness_RDOtherDisc

replace koef=koef*3*(27-20+1)
replace lower=lower*3*(27-20+1)
replace upper=upper*3*(27-20+1)

replace koef=koef*100   if var=="firstpsyc"
replace lower=lower*100 if var=="firstpsyc"
replace upper=upper*100 if var=="firstpsyc"

foreach var in firstpsyc  inpat outpat er {
	
if ("`var'"=="firstpsyc") {
local ytit "Percentage points"
local tit "Psychologist"
}
if ("`var'"!="firstpsyc") {
local ytit "Number of services"
local ylab "ylabel(-0.4(0.1)0.3,labsize(medium))"
}
if ("`var'"=="er") {
local tit "Emergency room visits"
}
if ("`var'"=="outpat") {
local tit "Outpatient hospital contacts"
}
if ("`var'"=="inpat") {
local tit "Inpatient hospital contacts"
}

twoway (rcap lower upper cutoff if var=="`var'", color(gs7)) (scatter koef cutoff if var=="`var'" & cutoff!=38, mcolor(black) mfcolor(white)) ///
		(scatter koef cutoff if var=="`var'" & cutoff==38, mcolor(red)) , ///		
	    graphregion(color(white))  xsize(5) ysize(5) xtitle("Age",size(medium)) ytitle("`ytit'",size(medium)) xscale(titlegap(*4)) yscale(titlegap(*4)) ///
		legend(order(2 3 1) label(2 "Placebo estimate") label(3 "Policy estimate") label(1 "95% CI") rows(1) pos(6) region(color(white)) size(small)) yline(0, lcolor(black)) ///
		name(`var',replace) title("`tit'", size(medium) color(black)) xlabel(,labsize(medium)) ylabel(,labsize(medium))

}

grc1leg firstpsyc er outpat inpat, iscale(*0.9) graphregion(color(white)) rows(2) legendfrom(firstpsyc)

graph export "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RD_OtherDisc.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RD_OtherDisc.eps", replace 


/*********************/
/********* 32 ********/
/*********************/

clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,18,50)
keep if inrange(distyrm,-5,7)

keep pnr dupli distyrm treatagec tyrm yrm agec docvisit specdoc medphyc inpat outpat er psyc Dpsyc firstpsyc 

foreach var in docvisit specdoc medphyc inpat outpat er {
replace `var'=0 if `var'<0 | mi(`var')
}

/* Winzorize */
foreach var in docvisit specdoc medphyc inpat outpat er {
qui sum `var' if `var'>0 & !mi(`var'), d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

keep if distyrm<2
gcollapse (mean) Dpsyc firstpsyc docvisit specdoc medphyc inpat outpat er, by(pnr pnrg distyrm treatagec tyrm yrm) fast
keep if inrange(treatagec,28,46)

egen distg=group(distyrm)
egen yrmg=group(yrm)

/** Create postshock dummies **/

sum distg 
global max=r(max)
global maxm1=r(max)-1

/* set base group to three periods before treatment */
sum distg if distyrm==0
global bdist=3
global base=r(max)-${bdist}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

g byte postreform=(tyrm>=2008.25)
g byte postshock=(distyrm>=0) & !mi(distyrm)

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

/* Estimates */
cap postclose john
postfile john str30 var post koef lower upper using "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RD_PrePeriodPlacebo", replace

foreach p in 0 1 {

	foreach var in firstpsyc inpat outpat er {
		
	qui aregben `var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  1.postshock#1.above  [pw=kwt] if treatage!=38 & postreform==`p', vce(cluster pnr) absorb(pnrg)
	
	post john ("`var'") (`p') (_b[1.postshock#1.above]) (_b[1.postshock#1.above]-1.96*_se[1.postshock#1.above]) (_b[1.postshock#1.above]+1.96*_se[1.postshock#1.above])
	}

}
postclose john



/** Figures **/
clear all
cd "I:\Workdata\706727\Figs"
use Final_PhysicalLabor_Robustness_RD_PrePeriodPlacebo

replace koef=koef*3*(27-20+1)
replace lower=lower*3*(27-20+1)
replace upper=upper*3*(27-20+1)

replace koef=koef*100   if var=="firstpsyc"
replace lower=lower*100 if var=="firstpsyc"
replace upper=upper*100 if var=="firstpsyc"

gen john=.
local i=1
foreach var in firstpsyc er outpat inpat  {
replace john=`i' if var=="`var'"
local i=`i'+1
}

label define john 1 "Psychologist" 2 "Emergency room" 3 "Outpatient hosp." 4 "Inpatient hosp." 

label values john john

twoway (rcap lower upper john if post==0 & var=="firstpsyc", color(gs7) yaxis(1)) (scatter koef john if post==0 & var=="firstpsyc", mcolor(black) mfcolor(white) yaxis(1)) ///
		(rcap lower upper john if post==1 & var=="firstpsyc", color(red) yaxis(1)) (scatter koef john if post==1 & var=="firstpsyc", mcolor(red)  yaxis(1)) ///
		(rcap lower upper john if post==0 & var!="firstpsyc", color(gs7)  yaxis(2)) (scatter koef john if post==0 & var!="firstpsyc", mcolor(black) mfcolor(white) yaxis(2)) ///
		(rcap lower upper john if post==1 & var!="firstpsyc", color(red)  yaxis(2)) (scatter koef john if post==1 & var!="firstpsyc", mcolor(red)  yaxis(2)) ///
	    ,graphregion(color(white))  xtitle("") ytitle("`ytit'",size(medium)) xscale(titlegap(*4)) yscale(titlegap(*4)) ///
		legend(order(2 4) label(2 "Placebo estimate 2003-2007") label(4 "Policy estimate 2008-2011")  rows(2) ring(0) pos(1) region(color(white)) ) yline(0, lcolor(black)) ///
		name(`var',replace) title("`tit'", size(medium) color(black)) xlabel(1(1)4,labsize(medium) valuelabel angle(60)) ylabel(-10(5)15,labsize(medium) axis(1)) ylabel(-0.1(0.05)0.15,labsize(medium) axis(2)) ///
		ytitle("Percentage points (psychologist)", axis(1)) ytitle("Number of services (other outcomes)", axis(2))


graph export "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RD_PrePeriod.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\Final_PhysicalLabor_Robustness_RD_PrePeriod.eps", replace 


/*********************/
/********* 33 ********/
/*********************/

clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,18,50)
keep if inrange(distyrm,-5,0)
keep if !inrange(tyrm,2008,2008.25)

cap drop Dpsychiatry
gen Dpsychiatry=(psychiatry>0 & !mi(psychiatry))

keep pnr dupli distyrm treatagec tyrm yrm agec koen inc earn wealth Dpsyc Dtherapy Dpsychiatry Dpsykhosp Dadep Danxsleep Dsui Dpois_painkiller

gen male=(koen==1) if !mi(koen)

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

keep if distyrm<-1
gcollapse (mean) inc earn wealth Dpsyc Dtherapy Dpsychiatry Dpsykhosp Dadep Danxsleep Dsui male, by(pnr pnrg distyrm treatagec tyrm yrm) fast

egen distg=group(distyrm)
egen yrmg=group(yrm)
g byte postreform=(tyrm>=2008.25) & !mi(tyrm)

/*** Create table ***/
mat X=J(13,6,.)
mat stars=J(13,6,0)

/* RD-in-time */
g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=tyrm-2008.25
g byte above=(tyrm>=2008.25) if !mi(tyrm)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,4-abs(d))

egen tyrmg=group(tyrm)

sum tyrmg if tyrm==2008.25
global tyrm0=r(mean)
sum tyrmg
global tyrmmax=r(max)

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

preserve
keep if inrange(treatagec,18,27.99)

local i=1
local j=1
foreach var in male inc earn wealth Dpsyc Dtherapy Dpsychiatry Dpsykhosp Dadep Danxsleep Dsui  {
	
reg `var' 1.above c.zabove c.zbelow   [pw=kwt] , vce(cluster pnr)
mat X[`i',2]=_b[_cons]
	
reg `var' 1.above c.zabove#i.distg c.zbelow#i.distg i.distg i.yrmg   [pw=kwt] , vce(cluster pnr)

mat X[`i',1]=_b[1.above]
mat X[`i',3]=_se[1.above]
mat stars[`i',1]=(abs(_b[1.above]/_se[1.above])>1.645)+(abs(_b[1.above]/_se[1.above])>1.96) + (abs(_b[1.above]/_se[1.above])>2.58)

local i=`i'+1
}

restore

/* RD */
keep if inrange(tyrm,2008.25,2012.25)

cap drop above
g byte above=(treatagec<38) if !mi(treatagec)

cap drop dist
cap drop zabove zbelow
g double dist=treatagec-38
g double zabove=above*dist
g double zbelow=dist

cap drop kwt
g double kwt=max(0,7.5-abs(dist))

local i=1
foreach var in male inc earn wealth Dpsyc Dtherapy Dpsychiatry Dpsykhosp Dadep  Danxsleep Dsui  {
reg `var' 1.above c.zabove c.zbelow   [pw=kwt] if  treatagec!=38, vce(cluster pnr)
mat X[`i',5]=_b[_cons]
	
reg `var' 1.above c.zabove#i.distg c.zbelow#i.distg i.distg i.yrmg   [pw=kwt] if  treatagec!=38, vce(cluster pnr)

mat X[`i',4]=_b[1.above]
mat X[`i',6]=_se[1.above]
mat stars[`i',4]=(abs(_b[1.above]/_se[1.above])>1.645)+(abs(_b[1.above]/_se[1.above])>1.96) + (abs(_b[1.above]/_se[1.above])>2.58)

local i=`i'+1
}

mat Y=X
foreach k in 1 5 6 7 8 9 10 11 12 13 {
mat Y[`k',1]=Y[`k',1]*100	
mat Y[`k',2]=Y[`k',2]*100
mat Y[`k',3]=Y[`k',3]*100	
mat Y[`k',4]=Y[`k',4]*100
mat Y[`k',5]=Y[`k',5]*100	
mat Y[`k',6]=Y[`k',6]*100

}
mat Y=Y[1..4,1..6]\J(1,6,.)\Y[5..12,1..6]
mat starsf=stars[1..4,1..6]\J(1,6,0)\stars[5..12,1..6]


frmttable using I:\workdata\706727\Figs\Final_PhysicalLabor_CharacteristicsChange.tex, tex fragment replace statmat(Y) sub(2) annotate(starsf) asymbol(*,**,***) brackets("","" \ [,] \ (,)) coljust(l c)  ///
ctitle("", "RD-in-time","RD" \ "", "18-27","37") ///
sdec(2\2\2\0\0\0\0\0\0\0\0\0\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2) rtitle("Percent male" \ ""  \ "" \ "Avg. Income" \ ""  \ ""  \ "Avg. earnings" \ ""  \ ""  \ "Avg. wealth" \ ""  \ "" \ "Share previous mental health problems:"  \ ""  \ "" \ "Psychologist" \ ""  \ "" \ "PCP MH consulation" \ ""  \ "" \ "Psychiatrist" \ ""  \ "" \ "Psychiatric hospital"  \ ""  \ "" \  "Antidepressants" \ ""   \ "" \ "Anxiety  & tranquilizers" \ ""  \ "" \ "Suicide attempts" \ ""  \ "" ) 

frmttable using I:\workdata\706727\Figs\Final_PhysicalLabor_CharacteristicsChange.rtf, replace statmat(Y) sub(2) annotate(starsf) asymbol(*,**,***)  brackets("","" \ [,] \ (,)) coljust(l c)  ///
ctitle("", "RD-in-time","RD" \ "", "18-27","37") ///
sdec(2\2\2\0\0\0\0\0\0\0\0\0\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2) rtitle("Percent male" \ ""  \ "" \ "Avg. Income" \ ""  \ ""  \ "Avg. earnings" \ ""  \ ""  \ "Avg. wealth" \ ""  \ "" \ "Share previous mental health problems:"  \ ""  \ "" \ "Psychologist" \ ""  \ "" \ "PCP MH consulation" \ ""  \ "" \ "Psychiatrist" \ ""  \ "" \ "Psychiatric hospital"  \ ""  \ "" \  "Antidepressants" \ ""   \ "" \"Anxiety  & tranquilizers" \ ""  \ "" \ "Suicide attempts" \ ""  \ "" ) 


/*********************/
/********* 34 ********/
/*********************/

/**** Data Preb estimates ****/
clear 
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,18,50)
keep if inrange(distyrm,-5,7)

keep pnr dupli distyrm treatagec tyrm yrm agec docvisit specdoc medphyc inpat outpat er psyc Dpsyc firstpsyc 

foreach var in psyc docvisit specdoc medphyc inpat outpat er {
replace `var'=0 if `var'<0 | mi(`var')
}

/* Winzorize */
foreach var in psyc docvisit specdoc medphyc inpat outpat er {
qui sum `var' if `var'>0 & !mi(`var'), d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
}

keep if inrange(tyrm,2008.25,2012.25)
keep if inrange(treatagec,30,47)

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

foreach var in firstpsyc psyc docvisit specdoc medphyc inpat outpat er  {
rename `var' real`var'
}

gcollapse (mean) real*, by(pnr pnrg dupli distyrm treatagec tyrm yrm) fast

* Merge with outcome predictions *
merge 1:1 pnr dupli distyrm using MLOutPred
keep if _merge==3
drop _merge 

g byte treat=(inrange(treatagec,18,37.99))

egen distg=group(distyrm)
egen yrmg=group(yrm)
g byte postreform=(tyrm>=2008.25) & !mi(tyrm)

/** Create postshock dummies **/

sum distg 
global max=r(max)
global maxm1=r(max)-1

sum distg if distyrm==0
global base=r(max)-1

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

cap drop bgdistg2
gen bgdistg2=distg
replace bgdistg2=${max} if distg==${base}
replace bgdistg2=${base} if distg==${max}


compress

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))
destring(pnr), gen(numpnr)

* Reduced form  *
foreach var in firstpsyc  {

* Real *
qui aregben real`var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  1.postshock#1.above  [pw=kwt] if treatage!=38, vce(cluster pnr) absorb(pnrg)

global est_RD_`var'=_b[1.postshock#1.above]*3*(48-20+1)*100
global se_RD_`var'=_se[1.postshock#1.above]*3*(48-20+1)*100

* Placebo *
qui aregben real`var' i.yrmg ib${base}.bgdistg c.`var' ib${base}.bgdistg#c.`var' ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  1.postshock#1.above  [pw=kwt] if treatage!=38, vce(cluster pnr) absorb(pnrg)

global est_RD_Pla_`var'=_b[1.postshock#1.above]*3*(48-20+1)*100
global se_RD_Pla_`var'=_se[1.postshock#1.above]*3*(48-20+1)*100

}

* IV *
foreach var in  psyc docvisit specdoc medphyc inpat outpat er  {

* Real *
qui ivreghdfe real`var'  ib${base}o1.distg#c.zabove ib${base}o1.distg#c.zbelow (realfirstpsyc=1.postshock#1.above)  [pw=kwt] if treatage!=38 ,cluster(numpnr)  absorb(pnrg yrmg distg)

global est_RD_`var'=_b[realfirstpsyc]
global se_RD_`var'=_se[realfirstpsyc]

* Placebo *
qui ivreghdfe real`var' c.`var' ib${base}o1.distg#c.`var' ib${base}o1.distg#c.zabove ib${base}o1.distg#c.zbelow (realfirstpsyc=1.postshock#1.above)  [pw=kwt] if treatage!=38 ,cluster(numpnr)  absorb(pnrg yrmg distg)

global est_RD_Pla_`var'=_b[realfirstpsyc]
global se_RD_Pla_`var'=_se[realfirstpsyc]

}

/*** Within two years ***/
keep if distyrm<2

* Reduced form  *
foreach var in firstpsyc  {

* Real *
qui aregben real`var' i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  1.postshock#1.above  [pw=kwt] if treatage!=38, vce(cluster pnr) absorb(pnrg)

global est_RD2_`var'=_b[1.postshock#1.above]*3*(28-20+1)*100
global se_RD2_`var'=_se[1.postshock#1.above]*3*(28-20+1)*100

* Placebo *
qui aregben real`var' i.yrmg ib${base}.bgdistg c.`var' ib${base}.bgdistg#c.`var' ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  1.postshock#1.above  [pw=kwt] if treatage!=38, vce(cluster pnr) absorb(pnrg)

global est_RD2_Pla_`var'=_b[1.postshock#1.above]*3*(28-20+1)*100
global se_RD2_Pla_`var'=_se[1.postshock#1.above]*3*(28-20+1)*100

}

* IV *
foreach var in  psyc docvisit specdoc medphyc inpat outpat er  {

* Real *
qui ivreghdfe real`var'  ib${base}o1.distg#c.zabove ib${base}o1.distg#c.zbelow (realfirstpsyc=1.postshock#1.above)  [pw=kwt] if treatage!=38 ,cluster(numpnr)  absorb(pnrg yrmg distg)

global est_RD2_`var'=_b[realfirstpsyc]
global se_RD2_`var'=_se[realfirstpsyc]

* Placebo *
qui ivreghdfe real`var' c.`var' ib${base}o1.distg#c.`var' ib${base}o1.distg#c.zabove ib${base}o1.distg#c.zbelow (realfirstpsyc=1.postshock#1.above)  [pw=kwt] if treatage!=38 ,cluster(numpnr)  absorb(pnrg yrmg distg)

global est_RD2_Pla_`var'=_b[realfirstpsyc]
global se_RD2_Pla_`var'=_se[realfirstpsyc]

}


/** Create table **/
mat X=J(8,8,.)
mat stars=J(8,8,0)

local j=1
foreach met in RD2 RD2_Pla RD RD_Pla  {
	
	local i=1
	foreach var in firstpsyc psyc docvisit specdoc medphyc inpat outpat er {
	
	cap mat X[`i',`j']=${est_`met'_`var'}
	cap mat X[`i',`j'+1]=${se_`met'_`var'}

	cap mat stars[`i',`j']=(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.645)+(abs(${est_`met'_`var'}/${se_`met'_`var'})>1.96) + (abs(${est_`met'_`var'}/${se_`met'_`var'})>2.58)
	
	local i=`i'+1
	}
local j=`j'+2
}

frmttable using "I:\workdata\706727\Figs\LabormarketTable_MLPlacebo.tex", tex fragment replace statmat(X) sub(1) annotate(stars) asymbol(*,**,***) brackets("","" \ (,))  coljust(l c)  ///
ctitle("Post-shock period","Within 2 years", "","Within 7 years", "" \ "Method","Baseline", "Incl. prediction controls","Baseline", "Incl. prediction controls")   ///
sdec(2) rtitle(" Psychologist (share)" \ " " \"Psychologist (services)" \ " "  \ "PCP visit" \ " "   \  "Specialist visit" \ " " \  "Somatic drugs" \ " "  \  "Inpatient visit" \ " " \  "Outpatient visit" \ " " \ "ER visit" \ " ")


frmttable using "I:\workdata\706727\Figs\LabormarketTable_MLPlacebo.rtf",   replace statmat(X) sub(1) annotate(stars) asymbol(*,**,***) brackets("",""  \ (,))  coljust(l c) ///
ctitle("Post-shock period","Within 2 years", "","Within 7 years", "" \ "Method","Baseline", "Incl. prediction controls","Baseline", "Incl. prediction controls")   ///
sdec(2) rtitle(" Psychologist (share)" \ " " \"Psychologist (services)" \ " "  \ "PCP visit" \ " "   \  "Specialist visit" \ " " \  "Somatic drugs" \ " "  \  "Inpatient visit" \ " " \  "Outpatient visit" \ " " \ "ER visit" \ " ")


/*********************/
/********* 35 ********/
/*********************/

/**** Based on Psychometric tests ****/
clear all
cd "I:\workdata\706727\Build\Data"
use PsykTestLongRunRD, clear

keep if inrange(treatagec,18,50)
keep if inrange(distyrm,-5,7)

keep pnr dupli distyrm treatagec tyrm yrm agec docvisit specdoc medphyc inpat outpat er psyc Dpsyc firstpsyc Ddisab Dsick Dallnonparleave 

foreach var in psyc docvisit specdoc medphyc inpat outpat er {
replace `var'=0 if `var'<0 | mi(`var')
}

/* Winzorize */
foreach var in psyc docvisit specdoc medphyc inpat outpat er {
qui sum `var' if `var'>0 & !mi(`var'), d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
}
egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

keep if inrange(tyrm,2008.25,2012.25)
keep if inrange(treatagec,30,47)

gcollapse (mean) psyc firstpsyc docvisit specdoc medphyc inpat outpat er Ddisab Dsick Dallnonparleave , by(pnrg distyrm treatagec tyrm yrm) fast

g byte treat=(inrange(treatagec,18,37.99))

egen distg=group(distyrm)
egen yrmg=group(yrm)
g byte postreform=(tyrm>=2008.25) & !mi(tyrm)

/** Create postshock dummies **/

sum distg 
global max=r(max)
global maxm1=r(max)-1

sum distg if distyrm==0
global base=r(max)-1

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

compress

keep if inrange(tyrm,2008.25,2012.25)

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

/*** Create table ***/
mat X=J(12,6,.)
mat stars=J(12,6,0)

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

* First stage *
local j=1
local i=1

* Baseline 
foreach var in firstpsyc docvisit specdoc medphyc inpat outpat er Dsick Ddisab Dallnonparleave {
		
reg `var' c.zbelow c.zabove 1.above ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${base}.distg#1.above [pw=kwt]

global baseprob_RD_`var'=0
forvalues y=20/48 {
global baseprob_RD_`var'=${baseprob_RD_`var'} +(_b[_cons]+_b[`y'.distg])*3	
}
}

* Estimate
qui aregben firstpsyc i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  1.postshock#1.above  [pw=kwt] if treatage!=38, vce(cluster pnr) absorb(pnrg)
eststo reg1

mat X[`i',`j']=_b[1.postshock#1.above]*3*(48-20+1)*100
mat X[`i',`j'+1]=${baseprob_RD_firstpsyc}*100
mat X[`i',`j'+2]=_se[1.postshock#1.above]*3*(48-20+1)*100
mat stars[`i',`j']=(abs(_b[1.postshock#1.above]/_se[1.postshock#1.above])>1.645)+(abs(_b[1.postshock#1.above]/_se[1.postshock#1.above])>1.96) + (abs(_b[1.postshock#1.above]/_se[1.postshock#1.above])>2.58)

* Number of psychologist services stage *
local j=1
local i=2
qui ivreghdfe psyc  ib${base}o1.distg#c.zabove ib${base}o1.distg#c.zbelow (firstpsyc=1.postshock#1.above)  [pw=kwt] if treatage!=38 ,cluster(pnr)  absorb(pnrg yrmg distg)
eststo reg1

mat X[`i',`j']=_b[firstpsyc]
mat X[`i',`j'+2]=_se[firstpsyc]
mat stars[`i',`j']=(abs(_b[firstpsyc]/_se[firstpsyc])>1.645)+(abs(_b[firstpsyc]/_se[firstpsyc])>1.96) + (abs(_b[firstpsyc]/_se[firstpsyc])>2.58)

* Second stage *
local i=3
foreach var in docvisit specdoc medphyc inpat outpat er Dsick Ddisab Dallnonparleave  {

qui ivreghdfe `var'  ib${base}o1.distg#c.zabove ib${base}o1.distg#c.zbelow (firstpsyc=1.postshock#1.above)  [pw=kwt] if treatage!=38 ,cluster(pnr)  absorb(pnrg yrmg distg)

mat X[`i',`j']=_b[firstpsyc]
mat X[`i',`j'+2]=_se[firstpsyc]
mat stars[`i',`j']=(abs(_b[firstpsyc]/_se[firstpsyc])>1.645)+(abs(_b[firstpsyc]/_se[firstpsyc])>1.96) + (abs(_b[firstpsyc]/_se[firstpsyc])>2.58)

mat X[`i',`j'+1]=${baseprob_RD_`var'}

local i=`i'+1
}

/**** Based on PCP MHC ****/
clear 
cd "I:\workdata\706727\Build\Data"
use TherapyLongRunRD, clear

keep if inrange(tyrm,2003.25,2012.25)
keep if inrange(treatagec,18,50)
keep if inrange(distyrm,-5,7)

keep pnr dupli distyrm treatagec tyrm yrm agec docvisit specdoc medphyc inpat outpat er psyc Dpsyc firstpsyc Ddisab Dsick Dallnonparleave

foreach var in psyc docvisit specdoc medphyc inpat outpat er {
replace `var'=0 if `var'<0 | mi(`var')
}

/* Winzorize */
foreach var in psyc docvisit specdoc medphyc inpat outpat er {
qui sum `var' if `var'>0 & !mi(`var'), d
replace `var'=r(p99) if `var'>r(p99) & !mi(`var')
}

egen pnrg=group(pnr dupli)

replace yrm=floor(yrm*4)/4
replace tyrm=floor(tyrm*4)/4
cap drop distyrm*
gen distyrm=yrm-tyrm

keep if inrange(tyrm,2008.25,2012.25)
keep if inrange(treatagec,30,47)

gcollapse (mean) psyc firstpsyc docvisit specdoc medphyc inpat outpat er Ddisab Dsick Dallnonparleave , by(pnrg distyrm treatagec tyrm yrm) fast

g byte treat=(inrange(treatagec,18,37.99))

egen distg=group(distyrm)
egen yrmg=group(yrm)
g byte postreform=(tyrm>=2008.25) & !mi(tyrm)

/** Create postshock dummies **/

sum distg 
global max=r(max)
global maxm1=r(max)-1

sum distg if distyrm==0
global base=r(max)-1

cap drop distgpoolpre
gen distgpoolpre=distg
replace distgpoolpre=${max} if distg<=${base}
replace distgpoolpre=${base} if distg==${max}

cap drop bgdistg
gen bgdistg=distg
replace bgdistg=${max} if distg==${base}
replace bgdistg=${base} if distg==${max}
replace bgdistg=${max}-1 if distg==1
replace bgdistg=1 if distg==${max}-1

compress

keep if inrange(tyrm,2008.25,2012.25)

g byte postshock=(distyrm>=0) & !mi(distyrm)

cap drop d above zabove zbelow 
g double d=treatagec-38
g byte above=(treatagec<38) if !mi(treatagec)
g double zabove=above*d
g double zbelow=d

cap drop kwt
g double kwt=max(0,7.5-abs(d))

cap program drop aregben Estimate Replay
do "I:\Workdata\706727\STATA Programs\aregben.do"

* First stage *
local j=4
local i=1

* Baseline 
foreach var in firstpsyc docvisit specdoc medphyc inpat outpat er Dsick Ddisab Dallnonparleave {
		
reg `var' c.zbelow c.zabove 1.above ib${base}.distg ib${base}.distg#c.zbelow ib${base}.distg#c.zabove ib${base}.distg#1.above [pw=kwt]

global baseprob_RD_`var'=0
forvalues y=20/48 {
global baseprob_RD_`var'=${baseprob_RD_`var'} +(_b[_cons]+_b[`y'.distg])*3	
}
}

* Estimate
qui aregben firstpsyc i.yrmg ib${base}.bgdistg ib${base}.bgdistg#c.zabove ib${base}.bgdistg#c.zbelow  1.postshock#1.above  [pw=kwt] if treatage!=38, vce(cluster pnr) absorb(pnrg)
eststo reg1

mat X[`i',`j']=_b[1.postshock#1.above]*3*(48-20+1)*100
mat X[`i',`j'+1]=${baseprob_RD_firstpsyc}*100
mat X[`i',`j'+2]=_se[1.postshock#1.above]*3*(48-20+1)*100
mat stars[`i',`j']=(abs(_b[1.postshock#1.above]/_se[1.postshock#1.above])>1.645)+(abs(_b[1.postshock#1.above]/_se[1.postshock#1.above])>1.96) + (abs(_b[1.postshock#1.above]/_se[1.postshock#1.above])>2.58)

* Number of psychologist services stage *
local j=4
local i=2
qui ivreghdfe psyc  ib${base}o1.distg#c.zabove ib${base}o1.distg#c.zbelow (firstpsyc=1.postshock#1.above)  [pw=kwt] if treatage!=38 ,cluster(pnr)  absorb(pnrg yrmg distg)
eststo reg1

mat X[`i',`j']=_b[firstpsyc]
mat X[`i',`j'+2]=_se[firstpsyc]
mat stars[`i',`j']=(abs(_b[firstpsyc]/_se[firstpsyc])>1.645)+(abs(_b[firstpsyc]/_se[firstpsyc])>1.96) + (abs(_b[firstpsyc]/_se[firstpsyc])>2.58)

* Second stage *
local i=3
foreach var in docvisit specdoc medphyc inpat outpat er Dsick Ddisab Dallnonparleave  {

qui ivreghdfe `var'  ib${base}o1.distg#c.zabove ib${base}o1.distg#c.zbelow (firstpsyc=1.postshock#1.above)  [pw=kwt] if treatage!=38 ,cluster(pnr)  absorb(pnrg yrmg distg)

mat X[`i',`j']=_b[firstpsyc]
mat X[`i',`j'+2]=_se[firstpsyc]
mat stars[`i',`j']=(abs(_b[firstpsyc]/_se[firstpsyc])>1.645)+(abs(_b[firstpsyc]/_se[firstpsyc])>1.96) + (abs(_b[firstpsyc]/_se[firstpsyc])>2.58)

mat X[`i',`j'+1]=${baseprob_RD_`var'}

local i=`i'+1
}

/*** Table ***/

frmttable using "I:\workdata\706727\Figs\LabormarketTable_TherapyCompare.tex", tex fragment replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c)  ///
ctitle("Measure of mental  health shock","Psychometric test (baseline)", "PCP MHC" )   ///
sdec(2) rtitle("Psychologist (share)" \ "" \ "" \"Psychologist (services)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" \ "Sick leave"\ "" \ "" \ "Disability pension" \ "" \ "" \ "Any labor market transfer" \ "" \ "" )

frmttable using "I:\workdata\706727\Figs\LabormarketTable_TherapyCompare.rtf",   replace statmat(X) sub(2) annotate(stars) asymbol(*,**,***) brackets("","" \ [,] \ (,))  coljust(l c) ///
ctitle("Measure of mental  health shock","Psychometric test (baseline)", "PCP MHC" )   ///
sdec(2) rtitle("Psychologist (share)" \ "" \ "" \"Psychologist (services)" \ "" \ ""  \ "PCP visit" \ "" \ ""   \  "Specialist visit" \ "" \ "" \  "Somatic drugs" \ "" \ ""  \  "Inpatient visit" \ "" \ "" \  "Outpatient visit" \ "" \ "" \ "ER visit" \ "" \ "" \ "Sick leave"\ "" \ "" \ "Disability pension" \ "" \ "" \ "Any labor market transfer" \ "" \ "" )


/*********************/
/********* 36 ********/
/*********************/

clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_final

keep if inrange(agec,18,58)

keep pnr year month agec birthyear birthmonth firstpsyc Dpsyc firstpsykhosp Dpsykhosp

gen yrm=year+(month-1)/12
keep if inrange(yrm,2006,2012.5) 
gen age2008=2008-birthyear+(4-birthmonth)/12

cap drop _merge
merge 1:1 pnr year month using "J:\workdata\706727\Temp\physicalhealth" , keepusing(pnr year month foed_dag docvisit  specdoc d_medphyc medphyc p_medphyc d_inpat n_inpat p_inpat d_outpat n_outpat p_outpat d_er n_er p_er psyc p_psyc)
keep if _merge==3
drop _merge

foreach var in docvisit specdoc medphyc n_inpat n_outpat n_er  {
qui sum year if !mi(`var') 
replace `var'=0 if mi(`var') & inrange(year,r(min),r(max))

gen byte D`var'=(`var'>0 & !mi(`var')) if inrange(year,r(min),r(max))
}
rename Dn_inpat Dinpat
rename Dn_outpat Doutpat
rename Dn_er Der
rename n_inpat inpat
rename n_outpat outpat
rename n_er er

foreach var in specdoc medphyc inpat outpat er {
sort pnr D`var' year month

by pnr: gen byte first`var'=((D`var'==1 & D`var'[_n-1]==1 & yrm-yrm[_n-1]>=1) | (D`var'==1 & D`var'[_n-1]==0)) if pnr[_n-1]==pnr 
}

/** Create diagnosis-specific variables **/
foreach var in inpat outpat er {
gen first`var'_nbirth=(first`var'==1 & floor(d_`var'/100)!=10)
gen D`var'_nbirth=(D`var'==1 & floor(d_`var'/100)!=10)
}

keep if inrange(yrm,2008.25,2012.25) 
keep if inrange(agec,20,50)

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

foreach var in firstspecdoc firstmedphyc firstinpat_nbirth firstoutpat_nbirth firster_nbirth {
	
if ("`var'"=="firstspecdoc") {
global  ploty`var'=16.5
global  plotx`var'=45
}
if ("`var'"=="firstmedphyc") {
global  ploty`var'=5.75
global  plotx`var'=27.5
}	
if ("`var'"=="firstinpat_nbirth") {
global  ploty`var'=6.75
global  plotx`var'=27.5
}		
if ("`var'"=="firstoutpat_nbirth") {
global  ploty`var'=14.5
global  plotx`var'=45
}		
if ("`var'"=="firster_nbirth") {
global  ploty`var'=14.5
global  plotx`var'=45
}		
		
preserve
keep if inrange(yrm,2008.25,2012.25)

replace `var'=`var'*12*100

/* Normal */
 reg `var' 1.above c.zabove c.zbelow   [pw=kwt] if  agec!=38, vce(cluster pnr)

global  dires`var': di %10.3f _b[1.above]
global  dibase`var': di %10.1f _b[_cons]
global  dise`var': di %10.3f _se[1.above]


/* Collapse data and create local linear trends */
gen weight=1
collapse (sum) weight (mean) `var' , by(agec) fast

/* Fit local linear regressions */
cap drop fitb
qui lpoly `var' agec  [aw=weight] if agec>=38 &  agec!=38,  k(tri) nograph gen(fitb) degree(1) at(agec) bwidth(7.5) 
qui replace fitb=. if agec<38

cap drop fita
qui lpoly `var' agec  [aw=weight] if agec<38 &  agec!=38,  k(tri) nograph gen(fita) degree(1) at(agec) bwidth(7.5) 
qui replace fita=. if agec>38


/* Graph */

replace agec=floor(agec*2)/2

collapse (mean)  `var' fita fitb [aw=weight], by(agec) fast

twoway (scatter  `var' agec , mcolor(red) msize(small))  ///
	  (line fita fitb agec , lcolor(black black) lwidth(*1.5 *1.5)) ///
	  ,xline(38, lcolor(red)) graphregion(color(white)) ///
	  text(${ploty`var'} ${plotx`var'} "Coefficient:${dires`var'}" "Baseline:  ${dibase`var'}  " "se:             ${dise`var'}" , box lcolor(white) fcolor(white)) ///
	  legend(off) xtitle("Age") ytitle("Percent starting treatment") ///
	  xscale(titlegap(*4)) yscale(titlegap(*6)) xsize(5) ysize(5)

graph export I:\workdata\706727\Figs\RDPhysHealth_`var'.png, width(2000) replace
graph export I:\workdata\706727\Figs\RDPhysHealth_`var'.eps, replace

restore
}

/*********************/
/********* 37 ********/
/*********************/

clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_final

keep if inrange(agec,18,58)

keep pnr year month agec birthyear birthmonth firstpsyc Dpsyc firstpsykhosp Dpsykhosp

gen yrm=year+(month-1)/12
keep if inrange(yrm,2006,2012.5) 
gen age2008=2008-birthyear+(4-birthmonth)/12

cap drop _merge
merge m:1 pnr year month using "J:\workdata\706727\Temp\extradata", keepusing(pnr year month sick disab grad sueduc cash_unemp2 cash_unemp cash_int educhelp sometrans dagp_unemp dagp_act ledyd forre re flexjob skaane intyd cash_dagexp  resf jobafk parleave)

keep if _merge==3

foreach var in sick disab {
qui sum year if !mi(`var') 
replace `var'=0 if mi(`var') & inrange(year,r(min),r(max))

gen byte D`var'=(`var'>0 & !mi(`var')) if inrange(year,r(min),r(max))
}
egen Dallnonparleave=rowmax(sick disab sueduc cash_unemp2 cash_unemp cash_int educhelp dagp_unemp dagp_act ledyd forre re flexjob skaane intyd cash_dagexp  resf jobafk)
replace grad=0 if mi(grad) & year>=2008 & !mi(year)
gen grademp=(grad>80) if !mi(grad)

foreach var in sick disab allnonparleave {
sort pnr D`var' year month

by pnr: gen byte first`var'=((D`var'==1 & D`var'[_n-1]==1 & yrm-yrm[_n-1]>=1) | (D`var'==1 & D`var'[_n-1]==0)) if pnr[_n-1]==pnr 
}
sort pnr year month
by pnr: gen byte empentry=(grademp==1 & grademp[_n+1]==1 & grademp[_n+2]==1 & grademp[_n-1]==0 & grademp[_n-2]==0 & grademp[_n-3]==0) if pnr[_n-1]==pnr & pnr[_n-2]==pnr & pnr[_n-3]==pnr & pnr[_n+1]==pnr & pnr[_n+2]==pnr & pnr[_n+3]==pnr 
by pnr: gen byte empexit= (grademp==0 & grademp[_n+1]==0 & grademp[_n+2]==0 & grademp[_n-1]==1 & grademp[_n-2]==1 & grademp[_n-3]==1)  if pnr[_n-1]==pnr & pnr[_n-2]==pnr & pnr[_n-3]==pnr & pnr[_n+1]==pnr & pnr[_n+2]==pnr & pnr[_n+3]==pnr 

* Convert to yearly rates *
cap drop maxempentry
by pnr year: egen maxempentry=max(empentry)
qui sum empentry if maxempentry==1
replace empentry=empentry*(1/r(mean))*100

cap drop maxempexit
by pnr year: egen maxempexit=max(empexit)
qui sum empexit if maxempexit==1
replace empexit=empexit*(1/r(mean))*100

keep if inrange(yrm,2008.25,2012.25) 
keep if inrange(agec,30,50)

/* Regression */
g byte above=(agec<38) if !mi(agec)
g byte below=(agec>=38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

foreach var in firstsick firstdisab firstallnonparleave empentry empexit {
	
if ("`var'"=="firstsick") {
global  ploty`var'=7.75
global  plotx`var'=45
}
if ("`var'"=="firstdisab") {
global  ploty`var'=0.35
global  plotx`var'=45
}	
if ("`var'"=="firstallnonparleave") {
global  ploty`var'=10
global  plotx`var'=45
}		
if ("`var'"=="empentry") {
global  ploty`var'=10
global  plotx`var'=45
}		
if ("`var'"=="empexit") {
global  ploty`var'=9
global  plotx`var'=45
}		
	
preserve
keep if inrange(yrm,2008.25,2012.25)

if (substr("`var'",1,5)=="first") {
replace `var'=`var'*12*100
}

/* Normal */
 reg `var' 1.above c.zabove c.zbelow   [pw=kwt] if  agec!=38, vce(cluster pnr)

global  dires`var': di %10.3f _b[1.above]
global  dibase`var': di %10.1f _b[_cons]
global  dise`var': di %10.3f _se[1.above]


/* Collapse data and create local linear trends */
gen weight=1
collapse (sum) weight (mean) `var' , by(agec) fast

/* Fit local linear regressions */
cap drop fitb
qui lpoly `var' agec  [aw=weight] if agec>=38 &  agec!=38,  k(tri) nograph gen(fitb) degree(1) at(agec) bwidth(7.5) 
qui replace fitb=. if agec<38

cap drop fita
qui lpoly `var' agec  [aw=weight] if agec<38 &  agec!=38,  k(tri) nograph gen(fita) degree(1) at(agec) bwidth(7.5) 
qui replace fita=. if agec>38


/* Graph */

replace agec=floor(agec*2)/2

collapse (mean)  `var' fita fitb [aw=weight], by(agec) fast

twoway (scatter  `var' agec , mcolor(red) msize(small))  ///
	  (line fita fitb agec , lcolor(black black) lwidth(*1.5 *1.5)) ///
	  ,xline(38, lcolor(red)) graphregion(color(white)) ///
	  text(${ploty`var'} ${plotx`var'} "Coefficient:${dires`var'}" "Baseline:  ${dibase`var'}  " "se:             ${dise`var'}" , box lcolor(white) fcolor(white)) ///
	  legend(off) xtitle("Age") ytitle("Percent") ///
	  xscale(titlegap(*4)) yscale(titlegap(*6)) xsize(5) ysize(5)

graph export I:\workdata\706727\Figs\RDLaborMarket`var'.png, width(2000) replace
graph export I:\workdata\706727\Figs\RDLaborMarket`var'.eps, replace

restore
}

/***** Graph with path to disab *****/
clear
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_final

keep if inrange(agec,18,58)

keep pnr year month agec birthyear birthmonth firstpsyc Dpsyc firstpsykhosp Dpsykhosp

cap drop _merge
cap drop _merge
merge m:1 pnr year month using "J:\workdata\706727\Temp\extradata", keepusing(pnr year month sick disab grad sueduc cash_unemp2 cash_unemp cash_int educhelp sometrans dagp_unemp dagp_act ledyd forre re flexjob skaane intyd cash_dagexp  resf jobafk parleave)
keep if _merge!=1
drop _merge

gen yrm=year+(month-1)/12
keep if inrange(yrm,2007.25,2020) 

egen Dallnonparleave=rowmax(sick disab sueduc cash_unemp2 cash_unemp cash_int educhelp dagp_unemp dagp_act ledyd forre re flexjob skaane intyd cash_dagexp  resf jobafk)
replace Dallnonparleave=0 if mi(Dallnonparleave)
drop sueduc cash_unemp2 cash_unemp cash_int educhelp dagp_unemp dagp_act ledyd forre re flexjob skaane intyd cash_dagexp  resf jobafk

replace grad=0 if mi(grad) & year>=2008 & !mi(year)
gen grademp=(grad>80) if !mi(grad)

foreach var in sick disab     {
replace `var'=0 if mi(`var')

gen byte D`var'=(`var'>0 & !mi(`var'))
}

sort pnr Dsick year month
cap drop firstsick
by pnr: gen byte firstsick=((Dsick==1 & Dsick[_n-1]==1 & yrm-yrm[_n-1]>=1) | (Dsick==1 & Dsick[_n-1]==0)) if pnr[_n-1]==pnr 

/*** RD dataset ***/
keep if inrange(yrm,2008.25,2020) 

sort pnr year month
by pnr: gen eps=sum(firstsick)

cap drop cyear
gen cyear=year+(month-1)/12

foreach var in Dsick Ddisab Dallnonparleave grademp {
	cap drop path`var'_0  
	gen byte path`var'_0=firstsick*`var'
	
	forvalues j=12(12)84 {	
	cap drop path`var'_`j'  
	by pnr: gen byte path`var'_`j'=(firstsick==1 & eps==eps[_n+`j'])*`var'[_n+`j'] if  (pnr==pnr[_n+`j'] & cyear[_n+`j']-cyear<=7)	
	}
}

keep if inrange(yrm,2008.25,2012.25) 
keep if inrange(agec,25,50)

/* Regressions */

g byte above=(agec<38) if !mi(agec)

g double dist=agec-38
g double zabove=above*dist
g double zbelow=dist

g double kwt=max(0,7.5-abs(dist))

cap postclose john
postfile john str30 var dist koef lower upper Tkoef Tlower Tupper Ckoef Clower Cupper using "I:\Workdata\706727\Figs\RDPathToDisab", replace

foreach var in Dsick Ddisab Dallnonparleave grademp {

	forvalues i=0(12)84 { 
	qui reg path`var'_`i' 1.above c.zabove c.zbelow   [pw=kwt] if  agec!=38 & inrange(yrm,2008.25,2012.25),  vce(cluster pnr)

	mat V=e(V)
	mat TV=V["1.above","1.above"]+V["_cons","_cons"]+2*V["1.above","_cons"]
	global Tse=sqrt(TV[1,1])
	
	post john ("`var'") (`i') (_b[1.above]) (_b[1.above]-1.96*_se[1.above]) (_b[1.above]+1.96*_se[1.above]) ///
		                      (_b[_cons]+_b[1.above]) (_b[_cons]+_b[1.above]-1.96*${Tse}) (_b[_cons]+_b[1.above]+1.96*${Tse}) ///
							  (_b[_cons]) (_b[_cons]-1.96*_se[_cons]) (_b[_cons]+1.96*_se[_cons]) 
	}
}
postclose john


/** Figures **/

preserve
clear
use "I:\Workdata\706727\Figs\RDPathToDisab"

foreach var in koef lower upper Tkoef Tlower Tupper Ckoef Clower Cupper {
replace `var'=`var'*12*100
} 
replace dist=dist/12

* Disability pension *

global var "Ddisab"

twoway (connect Ckoef Tkoef  dist if var=="${var}", color(black red) yaxis(1))  (rcap Tlower Tupper dist if var=="${var}",color(red) yaxis(1)) (rcap Clower Cupper dist if var=="${var}", color(black) yaxis(1)) ///
(connect koef  dist if var=="${var}", color(green) yaxis(2)) (rcap lower upper dist if var=="${var}", color(green) yaxis(2)) ///
,graphregion(color(white)) legend(order(2 "Treatment (left axis)" 1 "Control (left axis)" 5 "Difference (right axis)") rows(3) pos(11) ring(0) region(color(white))) xtitle("Years since start of spell") ///
ylabel(-0.1(0.1)0.2 , axis(1)) ylabel(-0.1(0.1)0.2 , axis(2)) ytitle("Percent", axis(1)) ytitle("Percentage points", axis(2)) yline(0, lcolor(black))

graph export "I:\Workdata\706727\Figs\RDLabormarket_PathtoDisab_Disability.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\RDLabormarket_PathtoDisab_Disability.eps", replace

* Sickness benefits *
global var "Dsick"

twoway (connect Ckoef Tkoef  dist if var=="${var}", color(black red) yaxis(1))  (rcap Tlower Tupper dist if var=="${var}",color(red) yaxis(1)) (rcap Clower Cupper dist if var=="${var}", color(black) yaxis(1)) ///
(connect koef  dist if var=="${var}", color(green) yaxis(2)) (rcap lower upper dist if var=="${var}", color(green) yaxis(2)) ///
,graphregion(color(white)) legend(order(2 "Treatment (left axis)" 1 "Control (left axis)" 5 "Difference (right axis)") rows(3) pos(1) ring(0) region(color(white))) xtitle("Years since start of spell") ///
ylabel(-2(2)8 , axis(1)) ylabel(-0.2(0.2)0.8 , axis(2)) ytitle("Percent", axis(1)) ytitle("Percentage points", axis(2)) yline(0, lcolor(black))

graph export "I:\Workdata\706727\Figs\RDLabormarket_PathtoDisab_Sick.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\RDLabormarket_PathtoDisab_Sick.eps", replace

* All transfers *
global var "Dallnonparleave"

twoway (connect Ckoef Tkoef  dist if var=="${var}", color(black red) yaxis(1))  (rcap Tlower Tupper dist if var=="${var}",color(red) yaxis(1)) (rcap Clower Cupper dist if var=="${var}", color(black) yaxis(1)) ///
(connect koef  dist if var=="${var}", color(green) yaxis(2)) (rcap lower upper dist if var=="${var}", color(green) yaxis(2)) ///
,graphregion(color(white)) legend(order(2 "Treatment (left axis)" 1 "Control (left axis)" 5 "Difference (right axis)") rows(3) pos(1) ring(0) region(color(white))) xtitle("Years since start of spell") ///
ylabel(-2(2)8 , axis(1)) ylabel(-0.2(0.2)0.8 , axis(2)) ytitle("Percent", axis(1)) ytitle("Percentage points", axis(2))  yline(0, lcolor(black))

graph export "I:\Workdata\706727\Figs\RDLabormarket_PathtoDisab_AllTrans.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\RDLabormarket_PathtoDisab_AllTrans.eps", replace

* Employment *
global var "grademp"

twoway (connect Ckoef Tkoef  dist if var=="${var}", color(black red) yaxis(1))  (rcap Tlower Tupper dist if var=="${var}",color(red) yaxis(1)) (rcap Clower Cupper dist if var=="${var}", color(black) yaxis(1)) ///
(connect koef  dist if var=="${var}", color(green) yaxis(2)) (rcap lower upper dist if var=="${var}", color(green) yaxis(2)) ///
,graphregion(color(white)) legend(order(2 "Treatment (left axis)" 1 "Control (left axis)" 5 "Difference (right axis)") rows(3) pos(1) ring(0) region(color(white))) xtitle("Years since start of spell") ///
ylabel(-2(2)8 , axis(1)) ylabel(-0.2(0.2)0.8 , axis(2)) ytitle("Percent", axis(1)) ytitle("Percentage points", axis(2)) yline(0, lcolor(black))

graph export "I:\Workdata\706727\Figs\RDLabormarket_PathtoDisab_Emp.png", replace width(2000)
graph export "I:\Workdata\706727\Figs\RDLabormarket_PathtoDisab_Emp.eps", replace

restore



